Sobes.tech
Junior — Middle

Milliseid meetodeid teate kasutajaliidese oleku salvestamiseks rakendustes?

sobes.tech AI

Vastus AI-lt

To save the state of the user interface in Android applications, the following methods are used:

  1. onSaveInstanceState(Bundle outState) and onRestoreInstanceState(Bundle savedInstanceState) — allow saving and restoring the state of an Activity or Fragment during their recreation (e.g., during screen rotation).

  2. ViewModel — stores data related to the UI and survives configuration changes without losing the state.

  3. SharedPreferences — used for saving simple data (settings, flags) between application sessions.

  4. Saving state in databases or files — for more complex or larger data.

  5. SavedStateHandle — in conjunction with ViewModel, allows saving and restoring UI state.

Example of saving the state of a text field in an Activity:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("input_text", editText.getText().toString());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    String text = savedInstanceState.getString("input_text");
    editText.setText(text);
}