0

Actually, I want to save my LinkedList in the saved instance so when a user opens the app again he can access the content already stored in the LinkedList. I know we need to convert the LinkedList into ArrayList in order to store it. While saving the ArrayList it gives me an error

wrong 2nd argument type in putParcelableArrayList(). Found 'java.util.ArrayList<java.lang.String>', required java.util.ArrayList<?extends android.os.Parcelable>.

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    ArrayList<String> arrayList = new ArrayList<String>(FavoriteQuotes);
    savedInstanceState.putParcelableArrayList("quotes",arrayList);
}

I know there are solutions available but it didn't seem to help me. Thanks.

mariuss
  • 1,177
  • 2
  • 14
  • 30
Ayush Bherwani
  • 2,409
  • 1
  • 15
  • 21

2 Answers2

2

You need to do like this

ArrayList<String> arrayList = new ArrayList<String>(FavoriteQuotes);
savedInstanceState.putStringArrayList("key",arrayList );
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Uday Ramjiyani
  • 1,407
  • 9
  • 22
0

You are getting that exception because FavoriteQuotes does not implement the Parcelable interface.

Both ArrayList and LinkedList implement the Serializable interface, which means there's a much easier way of persisting your LinkedList directly.

Assuming FavoriteQuotes is a LinkedList of Strings:

Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putSerializable("quotes", FavoriteQuotes);
}

When you restore it, you will need to call getSerializable, and cast it back to its original type:

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    FavoriteQuotes = (LinkedList) savedInstanceState.getSerializable("quotes");
}
Ovidiu
  • 8,204
  • 34
  • 45