简体   繁体   中英

Android AsyncTask: Adding views to an activity inside an AsyncTask?

I am working on aa search component to a twitter app. I have been doing the parsing in a regular class and tried to add views to the activity that way, but it didn't work. In my post:
Android 2.3.3: Crash when getting a LinearLayout from (LinearLayout)findViewById(R.id.<linear_layout_id>)
a very helpful stackoverflow user told me that my best choice would be putting all the parsing calls into an asynctask and adding the views to the activity on the onPostExecute().

So my question is, can I select a layout from the XML, add a view to it, and save it inside an asyctask's onPostExecute()?

yes off course, either pass the view or pass the Activity containing the view to the constructor of the AsyncTask. Just make sure you don't use those objects in the doInBackground method.

In fact I have done something similar just last week:

@Override
protected void onPostExecute(Article[] articles) {
    ArrayAdapter<Article> arrayAdapter = new ArticleAdapter(context, articles);
    listView.setAdapter(arrayAdapter);
    listView.setVisibility(View.VISIBLE);
    progressBar.setVisibility(View.GONE);
}

listView is a ListView passed as constructor argument same as context, which is the Context (activity) containing the view.

EDIT: Say you define AsyncTask then:

  • doInBackground has to return a Class3 object and take an array of Class1 objects (defined as Class1...) as argument
  • onProgressUpdate has to take an array of Class2 objects (defined as Class2...) as argument
  • onPostExecute has to take Class3 object as argument
  • ...

For more info you can read Android docs: http://developer.android.com/reference/android/os/AsyncTask.html

在onPostExecute中使用runOnUiThread(mRunnable)方法。如果你想对ui进行任何更改,将所有更改都改为runOnUiThread。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM