P
P
pmozil2015-06-07 18:04:16
Android
pmozil, 2015-06-07 18:04:16

How to keep ArrayList data in Adndroid on screen rotation?

There is a template class OwnClass.
MainActivity has an object of this ArrayList class.
How to save a view using onSaveInstanceState?

protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putStringArrayList("list", (ArrayList<>) output1);
    }

protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        ListView lv = (ListView) findViewById(R.id.listView);
        output1 = savedInstanceState.getStringArrayList("list");
        lv.setAdapter((new ArrayAdapter<OwnClass>(MainActivity.this,
        android.R.layout.simple_list_item_1, output1)));
    }

An error occurs that String is expected and OwnClass is found. And this is understandable, since the getStringArrayList method is used.
What method can be used to write and renew an ArrayList having objects of its own class?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Vasilenko, 2015-06-11
@farewell

It might be easier to use a static list by initializing it once:

staic ArrayList<MyItem> alm = null;

@Override
public void onCreate(Bundle sis) {
...
if (alm == null) {
  alm = new ArrayList<>();
  // Заполняем список
}
// Создаём ArrayAdapter с параметром alm, отдаём его ListView-у и т.д.
...
}

And if there are several fragments/activities of the same type, you can generally use a static list of lists:
static HashMap<String, ArrayList<MyItem>>

A
Alexander Vasilenko, 2016-06-04
@SanchelliosProg

You want your own class to implement the Parcelable interface , in which case it will be easy to store the collection in a Bundle SavedInstanceState and pull them out. Just write the object as ParcelableArrayList

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question