Keep data from a list when rotating on Android

Asked

Viewed 488 times

3

I started to study Android and I ended up falling into this problem.

I created a RecyclerView where it is fed by a field TextView, but every time I rotate the simulator, the values are reset.

I found some questions in Stackoverflow English but could not reproduce the same results in my test app.

I tried using the following methods, but it doesn’t work.

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);
    outState.putStringArrayList("myDataSet", myDataSet);
}

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

And when I try to hold onCreate() ends up crashing the app, saying that the List<> cannot be null

private ArrayList<String> myDataSet = new ArrayList<String>();

Part I call in the onCreate()

if(savedInstanceState != null){
    ArrayList<String> savedMyDataSet = savedInstanceState.getStringArrayList("myDataSet");
    myDataSet = savedMyDataSet;
} 

3 answers

3


Does not overwrite onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState). Instead it overwrites onSaveInstanceState(Bundle outState).

Ah, and in your case overwrite onRestoreInstanceState() is unnecessary.

1

Besides the answers given, a great option is the library IcePick.

Through annotations, you can easily define which variables you want to keep the state by eliminating the Boilerplate to save all your instances:

class Exemplo extends Activity {
    @State String nome; // Será automaticamente salvo usando essa anotação

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Icepick.restoreInstanceState(this, savedInstanceState);
    }

    @Override public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Icepick.saveInstanceState(this, outState);
    }
}

You can check out how it works in the official repository

0

In the archive AndroidManifest.xml, in your Activity statement add the following line:

android:configChanges="orientation|screenSize"

Example:

<activity
    android:name="com.example.activity.MainActivity"
    android:configChanges="orientation|screenSize"
    android:label="@string/app_name" >
</activity>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.