0

I'm using a listView and wants to restore/ resume the listView item/ state from where I had left (even after app closes). For this purpose I'm using

Parcelable state = listView.onSaveInstanceState();

the state is of Parcelable type because it returns result in parcelable type also while on restoring listView using

listView.onRestoreInstanceState(state);

it needs Parcelable type data as a parmeter. It works perfectly (using static variable) if user didn't closes the app. But I want to save this state data into SharedPreferences that will help the user to restore the listView even after closing the app.

I don't know how to store this state data into SharedPreferences. Please help me to solve this issue.

I also have tried this solution How Android SharedPreferences save/store object but it didn't solved my problem. The app is crashing on

Parcelable obj = gson.fromJson(json, Parcelable.class);

So, Please don't duplicate my question, If you know the solution just answer it.

Nauman Shafique
  • 433
  • 1
  • 6
  • 15

1 Answers1

0

I assume that your listview has an adapter that contains your required data so you can save that data somewhere (e.g. in sharedpreferences) instead of whole view's parcelable, e.g. if your adapter data is an ArrayList<ModelA> you can do something like this:

if ( listview.getAdapter() instanceof MyAdapter){
    MyAdapter adapter = (MyAdapter) listview.getAdapter();
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString( "adapterdata" , gson.toJson(adapter.getData()));
    editor.commit(); //or editor.apply()
}

and when you want to retrieve the data

String dataJson = prefs.getString( "adapterdata" , "");
ArrayList<ModelA> data = gson.fromJson( dataJson, new TypeToken<ArrayList<ModelA>>(){}.getType());

if ( data != null ){
    //set data to your listview, also it's logical to delete retrieved data from sharedpreferences
    SharedPreferences.Editor editor = prefs.edit();
    editor.remove("adapterdata");
    editor.commit();
}
Amin
  • 3,056
  • 4
  • 23
  • 34