aptyp
aptyp

Reputation: 251

AsyncTask crashes in doInBackground, add to listview

I get crash when i'm trying to run function doTask() in the background. I was trying with new Thread(new Runnable() {}) and it works only this section: handlerForBar.post(new Runnable() {public void run() { doTask(); } }) but the progressBar appears when the work of doTask() is finished. So I thought that AsyncTask could work, but it crashes.

  public void doTask() 
                {

                ListView listView = (ListView)findViewById(R.id.list);

                myArray = new ArrayList<HashMap<String,Object>>();
                HashMap<String, Object> hash_map;

                hash_map = new HashMap<String, Object>();
                hash_map.put(NICK_KEY, "nick");

                myArray.add(hash_map);
                listView.setAdapter(new myListAdapter(myArray,this));
                new myListAdapter(myArray,this).notifyDataSetChanged();
                }



private class myThread extends AsyncTask<String, Void, String> {

          @Override
          protected String doInBackground(String... params) {

              doTask(); //try, catch also FC
            return null;
          }

          ...
         }

Structure of *.java:

> public class mainActivity extends Activity{}
>                       public void onCreate()
>                                  new myThread().execute("");    
>                       public void doTask()
>                       private class myThread extends AsyncTask<String, Void, String>{}
>                                  protected String doInBackground()
>                                                   doTask()
>                       private class myListView extends BaseAdapter

Upvotes: 1

Views: 2754

Answers (2)

Mike Marshall
Mike Marshall

Reputation: 7850

You can't touch the UI in doInBackground, you have to update the UI in methods like onProgressUpdate or onPostExecute. See here

Upvotes: 2

waqaslam
waqaslam

Reputation: 68177

you cant manipulate ListView in doInBackground method. instead perform this in onPostExecute. In short, all the operations which require UI updates need to be done on UI thread and in AsyncTask it works in post execute

Hint: insert items in your adapter in doInBackground and then set it to list in onPostExecute

Upvotes: 2

Related Questions