In Android, you can save an Activity's state using the onSaveInstanceState()
method and then restore that state in the onCreate()
or onRestoreInstanceState()
method. This allows you to preserve data when an Activity is temporarily destroyed and recreated, such as during screen rotations or when the system reclaims resources. Here's an example of how to do it:
java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText editText;
private String savedText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
// Check if there's a saved state
if (savedInstanceState != null) {
savedText = savedInstanceState.getString("textKey");
editText.setText(savedText);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the state of your activity here
savedText = editText.getText().toString();
outState.putString("textKey", savedText);
}
}
In this example:
We have an
EditText
field where the user can input text.In the
onCreate()
method, we check if there's a saved state in thesavedInstanceState
bundle. If there is, we retrieve the saved text and set it to theEditText
.In the
onSaveInstanceState()
method, we save the state of theEditText
(in this case, the text entered by the user) into theoutState
bundle using a key-value pair. The key "textKey" is used to identify this piece of data.
By saving the state in onSaveInstanceState()
and restoring it in onCreate()
, you ensure that your Activity retains its state even when the system destroys and recreates it. This is particularly useful for preserving user input or other important data across configuration changes or interruptions.
Comments
Post a Comment