Skip to content Skip to sidebar Skip to footer

Having Trouble Restoring State On Listview

I have an app that allows the user to select an option and a certain list is displayed in a listview. I'm having issues with getting it to save and restore state. I have a list_m

Solution 1:

Well, since I got you into this mess.... :)

Something I do in situations like this is to pass in the saved instance state Bundle to the constructor for the adapter. Since you made your Item class Parcelable, everything else should be easy.

publicListAdapter(Bundle savedInstanceState) {

        if (savedInstanceState != null) {

            int ordinal = savedInstanceState.getInt("adapter_mode", 0);
            mListMode = ListMode.values()[ordinal];

            ArrayList<Item> items = 
                    savedInstanceState.getParcelableArrayList(KEY_ADAPTER_STATE);
            if (items != null) {
                setItems(items);
            }
        }
    }


    publicvoidonSaveInstanceState(Bundle outState) {
        outState.putInt("adapter_mode", mListMode.ordinal());
        outState.putParcelableArrayList(KEY_ADAPTER_STATE, mItems);
    }

So with the saved instance state in the constructor, you don't need an explicit method to restore the adapter state.

publicvoidsetItems(JSONArray jsonArray) throws JSONException {

        List<Item> items = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            items.add(new Item((JSONObject) jsonArray.get(i)));
        }
        setItems(items);
    }

    privatevoidsetItems(List<Item> items) {

        for (Item item : items) {
            mItems.add(item);
            if (item.getmType().equals("image")) {
                mImages.add(item);
            }
            if (item.getmType().equals("text")) {
                mTexts.add(item);
            }
        }

        notifyDataSetChanged();
     }

Solution 2:

Your app crashes if you call ListAdapter.getAllItems().clear() without calling ListAdapter.setItems() before

Cause: ListAdapter.getAllItems() may return null if mItems, mImages, mTexts are not initialized.

One workaround may be

publicclassListAdapterextends ... {
    ...privateArrayList<Item> mItems = new ArrayList<>();
    privateArrayList<Item> mImages = new ArrayList<>();
    privateArrayList<Item> mTexts = new ArrayList<>();
    ...
    }

Post a Comment for "Having Trouble Restoring State On Listview"