Reputation: 28063
Actually i use an AsyncTask for populating my ListView. Code looks like that:
private class MyAsyncTask extends AsyncTask<Void, Message, Void> {
ArrayAdapter<Message> adapter;
public MyAsyncTask{
adapter = ( ( ArrayAdapter<Message> ) mListView.getAdapter();
}
@Override
protected void onPreExecute () {
adapter.clear();
super.onPreExecute();
}
@Override
protected void onProgressUpdate ( Message... values ) {
adapter.add( values[0] );
super.onProgressUpdate( values );
}
@Override
protected Void doInBackground ( Void... params ) {
//Getting my messages
for ( Message message : messages ) {
publishProgress( message );
}
//Other heavy stuff
return null;
}
}
With traceview i saw that there is a big overhead due to the publishProgress called in a cycle. I thought that to modify code like that:
private class MyAsyncTask extends AsyncTask<Void, Message, Void> {
ArrayAdapter<Message> adapter;
List<Message> messages;
public MyAsyncTask{
adapter = ( ( ArrayAdapter<Message> ) mListView.getAdapter();
}
@Override
protected void onPreExecute () {
adapter.clear();
super.onPreExecute();
}
@Override
protected void onProgressUpdate ( Void... values ) {
for(Message message: messages){
adapter.add(message);
}
super.onProgressUpdate( values );
}
@Override
protected Void doInBackground ( Void... params ) {
messages = //Getting my messages
publishProgress();
//Other heavy stuff
return null;
}
}
This looks line more fast because there are less Messages to send between background thread and ui thread but i'm afraid to run into ANR if my List is very big. Any pattern to optimize this kind of problems?
Thanks :)
Upvotes: 0
Views: 426
Reputation: 1006869
With traceview i saw that there is a big overhead due to the publishProgress called in a cycle.
That is a bit surprising.
Any pattern to optimize this kind of problems?
Add the items to your adapter in doInBackground()
and do something else as a progress indicator, such as a ProgressBar
.
Upvotes: 1