Should the arraylist passed to an ArrayAdapter of

2019-08-31 03:41发布

The array list we pass to a custom array adapter are we supposed to modify it in a thread safe way?
I mean if I have private class MyAdapter extends ArrayAdapter<CustomObject> and I instantiate it with my ArrayList of CustomObjects if I later want to modify that array list or objects in the array list in order to then notify the adapter that the UI should be updated should I do it in a thread safe way? E.g. passing a synchronized array list?

3条回答
在下西门庆
2楼-- · 2019-08-31 04:22

If you modify the list on the main/UI thread, then go ahead. The ListView itself operates also on the UI thread.

If you change the list from another thread, you may have to handle synchronization issues. Though it should not cause any problems when the ListView is not scrolling, i.e. does not access the Adapter.

To change the list anytime from another thread, you have to post all changes to the UI thread.

// this code is executed in another thread
// e.g. download some data
// determine which list elements get changed

// post to UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
    public void run() {
        // change th actual list here and notifyDataSetChanged()
    }
});

If it's too complicated to determine what elements need to change, you also could create a new list and a new adapter:

// this code is executed in another thread
// e.g. download some data
// create a new list and/or a new adapter
final MyAdapter adapter = new MyAdapter(...);

// post to UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
    public void run() {
        // set the new adapter to the ListView
        listview.setAdapter(adapter);
    }
});
查看更多
一夜七次
3楼-- · 2019-08-31 04:32

No, the UI is updated in the UI thread when you call notifyDataSetChanged(). Its handled by android properly

查看更多
萌系小妹纸
4楼-- · 2019-08-31 04:41

Since it is a custom adapter,what if you were to maintain 2 array lists.

public ArrayList<CustomObject> modifiableList;
private ArrayList<CustomObject> adapterList;

and you do all your changes to the modifiableList,

Then when you can determine the user is not scrolling your UI, you can call notifyDatasetChangedCustom()

EDIT: if you are doing it from another thread,you could maintain a WeakReference to your adapter and then call the changes.

 public notifyDatasetChangedCustom(){
    this.adapterList=this.modifiableList;
    this.notifyDatasetChanged();
 }

You could also try looking into AsyncTaskLoader.This would take care addition of items and view updating automatically,although the implementation would be more complicated.

查看更多
登录 后发表回答