0

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 :))

2 Answers2

1

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,

  1. Either use Fragment
  2. 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);
    }
}
Ali
  • 519
  • 4
  • 13
0

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

  1. 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

  1. 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

  2. You can use ModelView to handle such scenarios. https://guides.codepath.com/android/Handling-Configuration-Changes#leveraging-viewmodels

Yauraw Gadav
  • 1,706
  • 1
  • 18
  • 39