Should the arraylist passed to an ArrayAdapter of a List be thread-safe?

醉酒当歌 提交于 2019-12-13 07:59:37

问题


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?


回答1:


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);
    }
});



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/29742009/should-the-arraylist-passed-to-an-arrayadapter-of-a-list-be-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!