5

Should the Arraylist switch to an ArrayAdapter from a list?

 3 years ago
source link: https://www.codesd.com/item/should-the-arraylist-switch-to-an-arrayadapter-from-a-list.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Should the Arraylist switch to an ArrayAdapter from a list?

advertisements

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?


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




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK