Keep data from a list when rotating on Android

2

I started studying Android and I ended up falling into this problem.

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

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

I tried to use the following methods, but it does not 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 get the onCreate() it ends up crashing the app, saying List<> can not be null

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

Part I call no onCreate()

if(savedInstanceState != null){
    ArrayList<String> savedMyDataSet = savedInstanceState.getStringArrayList("myDataSet");
    myDataSet = savedMyDataSet;
} 
    
asked by anonymous 08.09.2015 / 22:42

3 answers

3

Do not overwrite onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) . Instead, overwrite onSaveInstanceState(Bundle outState) .

Oh, and in your case overwriting onRestoreInstanceState() is unnecessary.

    
08.09.2015 / 23:55
1

In addition to the answers given, a great option is the IcePick library.

With annotations , you can easily define which variables you want to keep the state by eliminating boilerplate from saving 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 see how it works in the official repository

    
26.01.2016 / 15:44
0

In the file AndroidManifest.xml , in the declaration of your activity 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>
    
11.09.2015 / 21:04