Android – how do I call a method from the onclicklistener.onclick method?
•
Android
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLEncoder;
import com.google.gson.Gson;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class SampleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageButton button = (ImageButton) findViewById(R.id.imageButton1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
doSomething();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void doSomething() throws Exception {
EditText search2 = (EditText)findViewById(R.id.editText1);
TextView urltext = (TextView)findViewById(R.id.textView1);
String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String search = search2.toString() + "site:mysite.com";
String charset = "UTF-8";
URL url = new URL(google + URLEncoder.encode(search, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
String voidurlresult = results.getResponseData().getResults().get(0).getUrl().toString();
urltext.setText(voidurlresult);
}
}
Please look at the code above... What's the problem with the code. When I click the button, I get nothing. When I click the button, I want to get the URL of the first Google result... I would be grateful if someone could help me
resolvent:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
SampleActivity.this.doSomething();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Change the statement contained in the try statement to this. This will ensure that the correct class is referenced to call the method
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码