Crizly
Crizly

Reputation: 1009

android - Update ListView from AsyncTask doInBackground() thread

I have a thread doing some image processing which works fine, but periodically throughout the execution I want it to send strings to a ListView updating the user on the progress, I'm using the publishProgress() to display the strings, but I can't get it to dynamically update, only display everything at the end once the background task is done.

Background thread:

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    String message = "";
        for (String str : values) {
    message = str;
    }
    publishProgress.addItem(message); // Calls method in publishProgress.class with the update string.
}

The publishProgress class:

// Imports
public class publishProgress extends Activity 
{
public static ArrayAdapter<String> ad;
public static ArrayList <String> updates = new ArrayList <String>();
public static ListView list;
}
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     
    setContentView(R.layout.activity_publishProgress);

    ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, updates);
    list = (ListView)findViewById(R.id.listView1);
    list.setAdapter(ad);
}

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public static void addItem(String text) {
    updates.add(text);
    ad.notifyDataSetChanged();
}

The problem is I get a nullPointerException when calling ad.NotifyDataSetChanged();

I've not got much android experience so if anyone has any ideas how I can add strings to the ListView dynamically without freezing up the GUI it would be greatly appreciated.

Upvotes: 0

Views: 1038

Answers (1)

Lucian Novac
Lucian Novac

Reputation: 1265

On doInBackgroud() function make actions that depends on the network call, all the functions that depends to the UI implement them on onPostExecute() function becouse here you come back to the UI thread. So call notifyDataSetChanged() into onPostExecute()

Upvotes: 1

Related Questions