I have a RecyclerView with 2 layouts. There's an EditText in the first RecyclerView item. But when I rotate the device the EditText loses the data. (That is why we use ViewModel.) Should I use ViewModel for an adapter? (an example would be great :))
How to not lose EditText content when rotating the device - EditText is inside the RecyclerView item
2 Answers
In order to understand this behaviour you need to understand Activity Life Cycle
have deep knowledge and try to remember it, let me give a brief explanation.
Reason
It has been stated that **Whenever the Screen is Rotated the activity gets Destroyed and Recreated due to which the EditTexts loss data (loss state)
Solutions
there are two solutions for this,
- Either use Fragment
- Or try
onSaveInstanceState
I will only focus on the 2nd Method which will tell you how to solve this problem
Solution 2
public class MainActivity extends AppCompatActivity {
EditText editTextTest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextTest = findViewById(R.id.editTextTest);
if (savedInstanceState != null) {
testText = savedInstanceState.getString("editTextTest");
//Your State Restore Here
editTextTest.setText(testText);
}
}
@Override
protected void onSaveInstanceState(Bundle outState{
super.onSaveInstanceState(outState);
//Your State Sate here
outState.putString("editTextTest", text);
}
}

- 519
- 4
- 13
-
Yeah, but my EditText is inside the RecyclerView item. – Murad Ismayilov Sep 10 '20 at 06:40
So what happens when there is a configuration change e.g. when a device is rotated from landscape to portrait or vice verse is that Android OS destroys and recreates the Activity. i.e. onDestroy() > onCreate(), to handle this you can have 2 options
- Activity's onSaveInstanceState method to store the attributes that you don't want to lose in case of configuration changes, and restoring the attributes in on onRestoreInstanceState() or onCreate()
How to save an activity state using save instance state?
https://guides.codepath.com/android/Handling-Configuration-Changes#recyclerview
https://developer.android.com/guide/topics/resources/runtime-changes
You can also specify in the manifest file that you don't want your activity to be restarted in case of configuration changes and you will handle it manually by android:configChanges
You can use ModelView to handle such scenarios. https://guides.codepath.com/android/Handling-Configuration-Changes#leveraging-viewmodels

- 1,706
- 1
- 18
- 39