我从AsyncTaskActivity onPostExecute()方法内部调用setadapter()方法时遇到问题.我已经阅读了有关AsyncTask的文档:http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result)但是没有找到答案如何实现.我应该使用Intent吗?我是AndroID开发的新手,所以如果这是一个愚蠢的问题,请原谅我.
主要活动
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;}@OverrIDeprotected 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 Array等.
但是,如果仅从MainActivity调用AsyncTask,则更好的方法是使此AsyncTask成为MainActivity中的私有内部类.这将允许它访问MainActivity的所有全局变量和方法
总结以上是内存溢出为你收集整理的android – 从AsyncTask调用UI线程方法全部内容,希望文章能够帮你解决android – 从AsyncTask调用UI线程方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)