基本上我想知道我如何能够完成我在该主题中所写的内容。我浏览了很多关于 AsyncTask 的教程,但我无法让它工作。我有一个小表单(EditText),它将获取用户在那里输入的内容,并将其转换为 url 查询,供应用程序查找,然后显示结果。
我认为似乎可行的是:在我的主要活动中,我有一个名为 responseBody 的字符串。然后用户单击搜索按钮,它将转到我的搜索功能,并从那里调用带有 URL 的 GrabUrl 方法,该方法将启动 asyncdata,当该过程完成时,onPostExecute 方法将使用函数 activity.this.setResponseBody(content )。
这就是我的代码看起来最重要的部分(我认为)。
public class activity extends Activity {
private String responseBody;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
public void initControls() {
fieldSearch = (EditText) findViewById(R.id.EditText01);
buttonSearch = (Button)findViewById(R.id.Button01);
buttonSearch.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ search();
}});
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Void, String> {
private final HttpClient client = new DefaultHttpClient();
private String content;
private boolean error = false;
private ProgressDialog dialog = new ProgressDialog(activity.this);
protected void onPreExecute() {
dialog.setMessage("Getting your data... Please wait...");
dialog.show();
}
protected String doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
content = client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
error = true;
cancel(true);
} catch (IOException e) {
error = true;
cancel(true);
}
return content;
}
protected void onPostExecute(String content) {
dialog.dismiss();
if (error) {
Toast toast = Toast.makeText(activity.this, getString(R.string.offline), Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 0, 75);
toast.show();
} else {
activity.this.setResponseBody(content);
}
}
}
public void search() {
String query = fieldSearch.getText().toString();
String url = "http://example.com/example.php?query=" + query; //this is just an example url, I have a "real" url in my application but for privacy reasons I've replaced it
grabURL(url); // the method that will start the asynctask
processData(responseBody); // process the responseBody and display stuff on the ui-thread with the data that I would like to get from the asyntask but doesn't obviously
}