The problem here is that you are losing the "state" of the App. In OOPs, What is a State? The Variables! Exactly! Hence when you are losing the data of your variables.
Now here is what you can do, Find Out the variables which are losing their states.
When you rotate your device, your present activity gets completely destroyed, ie goes through onSaveInstanceState() onPause() onStop() onDestroy()
and a new activity is created completely which goes through onCreate() onStart()
onRestoreInstanceState.
The Two Methods in the bold, onSaveInstanceState() saves the instance of the present activity which is going to be destroyed. onRestoreInstanceState This method restores the saved state of the previous activity. This way you don't lose your previous state of the app.
Here is how you use these methods.
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putString("theWord", theWord); // Saving the Variable theWord
outState.putStringArrayList("fiveDefns", fiveDefns); // Saving the ArrayList fiveDefns
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
theWord = savedInstanceState.getString("theWord"); // Restoring theWord
fiveDefns = savedInstanceState.getStringArrayList("fiveDefns"); //Restoring fiveDefns
}
EDIT : A Better Approach: The above approach toward maintaining your data isn't the best way to maintain data in production code/apps. Google IO 2017 introduced ViewModel to protect your data against configurational changes (like Screen Rotation). Keeping all data inside the activity using variables isn't a good software design and violates the Single Responsibility Principle hence separate your data storage using ViewModel from the activities.
- ViewModel will be responsible for the data to be displayed.
- Activity will be responsible for how to display the data.
- Use additional repository class if you have an increasing complexity of storing the data.
That's just one of the way to separate classes and their responsibility, which will go a long way while making well-architectured apps.
onConfigurationChanged
stuff, see: #456711 – Phrase