【发布时间】:2011-10-02 14:18:42
【问题描述】:
我正在尝试实现以下逻辑:
用户在文本框中输入搜索字符串(一个活动) -> 调用 Web 服务以异步执行搜索 -> 搜索结果显示在列表中(另一个活动)
到目前为止,我有以下内容:
一个输入搜索字符串并点击“搜索”按钮的活动:
public class Search extends Activity
{
// ...
// called when "Search" button is clicked
private void runSearch()
{
ProgressDialog progressDialog = ProgressDialog.show(
this, "Search", "Search...");
searchAsyncTask = new SearchAsyncTask();
SearchAsyncTaskParam param = new SearchAsyncTaskParam();
param.SearchString = getSearchCode(); // gets input from text box
param.ProgressDialog = progressDialog;
searchAsyncTask.execute(param);
}
}
然后我有一个类来执行异步搜索:
public class SearchAsyncTask extends AsyncTask<SearchAsyncTaskParam,
Void, SearchAsyncTaskResult> {
private SearchAsyncTaskParam param;
@Override
protected SearchAsyncTaskResult doInBackground(
SearchAsyncTaskParam... params) {
if (params.length > 0)
param = params[0];
SearchAsyncTaskResult result = new SearchAsyncTaskResult();
// call Webservice and fill result object with status (success/failed)
// and a list of hits (each hit contains name, city, etc.)
return result;
}
@Override
protected void onPostExecute(SearchAsyncTaskResult result) {
param.ProgressDialog.dismiss();
if (!result.Success)
// throw an AlertBox
else
{
// this part is incomplete and doesn't look good, does it?
// And how would I pass my result data to the new activity?
Intent intent = new Intent(param.ProgressDialog.getContext(),
SearchResultList.class);
param.ProgressDialog.getContext().startActivity(intent);
}
}
}
最后一个元素是显示搜索结果列表的活动:
public class SearchResultList extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, data));
// String was only for testing, should be a class with holds the data
// for each item, i.e. Name, City, etc. And where do I get "data" from?
}
// ...
}
现在我的问题:
在
AsyncTask实例的onPostExecute方法中为结果列表启动活动是否是个好主意?我已经用上面勾勒的简单测试对其进行了测试,它似乎有效。但这安全吗,我在正确的线程(UI线程)上吗?如果这是不好的做法,那么启动结果活动的替代方法是什么?将
ProgressDialog的上下文用于Intent并启动活动看起来特别奇怪。这只是我在AsyncTask实例中可用的唯一上下文。这可能是一个问题,因为ProgressDialog已经被解雇了吗?我还可以使用什么上下文?如何将结果数据传递到
SearchResultList活动?
1234563用户返回到主屏幕(从中打开搜索活动)而不是
Search 活动。这可能吗?我该怎么做?
【问题讨论】:
标签: android android-activity android-asynctask listactivity