从AsyncTask调用UI线程方法

时间:2012-12-31 22:09:01

标签: android multithreading methods android-asynctask

我从AsyncTaskActivity onPostExecute()方法内部调用setadapter()方法时遇到问题。我已经阅读了有关AsyncTask的文档:http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result)但没有找到答案如何实现。我应该使用Intent吗?我是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

   }

}

2 个答案:

答案 0 :(得分:5)

假设您的AsyncTask始终由MainActivity调用,请执行此操作

protected void onPostExecute(Cursor cur) {
   MainActivity mActivity = (MainActivity) activity;
   mActivity.setadapter();
   }

您可以为setAdapter方法指定更多参数,以便您可以传递CursorString数组等。

然而,如果AsyncTask仅从MainActivity调用,则更好的方法是将此AsyncTask作为MainActivity内的私有内部类。这将允许它访问MainActivity

的所有全局变量和方法

答案 1 :(得分:0)

你的方法有点不寻常,但要回答问题:

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不是Activity,所以这个类名有点令人困惑......