我有一个问题,从AsyncTaskActivity的onPostExecute()方法内部调用setadapter()方法。我读过关于AsyncTask的文档:http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result),但没有找到如何实现这一目标的答案。我应该使用意向来这样做吗?我是Android开发的新手,所以如果这是一个愚蠢的问题,请原谅我。
MainActivity
public class MainActivity extends ListActivity {
private String[] columns = new String[] {"foreign_word", "native_word"};
private int[] target = new int[] { R.id.foreign_word, R.id.native_word };
private Cursor cur = null;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
new AsyncTaskActivity(this).execute();
}
public void setadapter(Cursor cur) {
SimpleCursorAdapter aaa = new SimpleCursorAdapter(this.getApplicationContext(), R.layout.list_entry, cur, columns, target, 0);
this.setListAdapter(aaa);
}
}
AsyncTaskActivity
public class AsyncTaskActivity extends AsyncTask<Void, Void, Cursor> {
Activity activity = null;
private SQLiteDatabase db = null;
private String[] selection = {"_id", "native_word", "foreign_word"};
Cursor cur = null;
public AsyncTaskActivity(Activity activity) {
this.activity = activity;
}
@Override
protected Cursor doInBackground(Void... params) {
DbAdapter mSQLadapter = new DbAdapter(activity);
db = mSQLadapter.getWritableDatabase();
Cursor cur = db.query("words", selection, "foreign_word='car'", null, null, null, null);
return cur;
}
protected void onPostExecute(Cursor cur) {
// I'd like to call setadapter() ,passing it Cursor as a parameter
}
}
假设你的AsyncTask总是被MainActivity
调用,那么
protected void onPostExecute(Cursor cur) {
MainActivity mActivity = (MainActivity) activity;
mActivity.setadapter();
}
您可以为您的setAdapter
方法指定更多参数,以便您可以传递Cursor
, String
数组等。
然而,如果AsyncTask
只能从MainActivity
调用,那么更好的方法是将AsyncTask
作为MainActivity
的私有内部类。这将允许它访问MainActivity
你的方法有点不寻常,但要回答所问的问题:
将activity
改为ListActivity:
ListActivity activity = null;
和使用:
protected void onPostExecute(Cursor cur) {
activity.setListAdapter(new SimpleCursorAdapter(activity, R.layout.list_entry, cur, columns, target, 0));
}
你应该考虑使用LoaderManager类,它为你创建和处理后台线程。你也应该考虑使用ContentProvider,它也为你处理了很多繁忙的工作。
最后AsyncTaskActivity不是一个活动,所以这个类的名字有点混乱…