I want to save the data in the activity in the edit text after returning in this activity. How to do it? Should I use a OnPause
and OnResume
??
Asked
Active
Viewed 82 times
-2

Nikitc
- 55
- 6
-
Use saveinstancestate to persist data while switching between activity – praveen dewangan Apr 23 '17 at 06:38
-
2Possible duplicate of [Saving Android Activity state using Save Instance State](http://stackoverflow.com/questions/151777/saving-android-activity-state-using-save-instance-state) – nomem Apr 23 '17 at 11:03
-
This question is a bit unclear. Please be more specific. – Stevoisiak Apr 23 '17 at 14:16
1 Answers
0
You can save the state of the application by using Bundle savedInstanceState. When we change the orientation of you device the data is lost.
In example below we save the value
int value = 1;
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
/* EditText editText =
(EditText) findViewById(R.id.editText);
CharSequence text = editText.getText();// getting text in edit text
outState.putCharSequence("savedText", text);// saved text in bundle object (outState)
*/
outState.putInt("value", value);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
/* CharSequence savedText=savedInstanceState.getCharSequence("savedText");
Toast.makeText(this, ""+savedText, Toast.LENGTH_SHORT).show();*/
value = savedInstanceState.getInt("value");
Toast.makeText(this, ""+value, Toast.LENGTH_SHORT).show();
}
public void buttonClicked(View view) {
value++;
}
XML Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:id="@+id/editText"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="buttonClicked"/>
</LinearLayout>
Note: Any information in Edit Text,Button etc will be persisted automatically by Android as long as you assign an ID. So 2nd edit text will clear its information but not Edit Text with id that is 1st Edit Text if you rotate the screen in above example.

Mukesh M
- 2,242
- 6
- 28
- 41