Search code examples
androidbackupfragmentorientation-changes

Best way to backup user's inputs dealing with orientation changes


I am developing a simple apps that allow users to post articles on a website.

It's just a simple form with inputs for title et text and a send button.

To do this, I used a FragmentActivity with a Fragment called ArticleFragment inside.

I've read everywhere that the best way to save user's inputs was to override onPause() in the fragment, and to restore them in the onCreateView().

@Override
public void onPause() {
    Log.i(TAG, "Pausing fragment");
    Log.i(TAG, "Saving edits");

    // Sauvegarde des saisies
    EditText titreEdit = (EditText) getActivity().findViewById(R.id.titre_saisie);
    EditText texteEdit = (EditText) getActivity().findViewById(R.id.texte_saisie);
    String titre = titreEdit.getText().toString();
    String texte = texteEdit.getText().toString();

    SharedPreferences settings = getActivity().getPreferences(0);
    Editor editor = settings.edit();
    editor.putString("titre", titre);
    editor.putString("texte", texte);
    editor.commit();

    Toast toast = Toast.makeText(getActivity(), R.string.article_enregistre, Toast.LENGTH_SHORT);
    toast.show();

    super.onPause();
}

As you can see, each time the activity is paused, a Toast is shown to inform the user that inputs have been saved.

That's what I wanted. But whenever the user changes the orientation of the screen, the popup is shown again (because Activity is paused, then destroyed) and this may annoye the user.

I tried to add android:configChanges="orientation" in the Manifest, but I think this is not the best way to deal with this issue.

I also tried to make a solution with onSaveInstance() but I do not understand how it works : sometimes onSavedInstance is null, sometimes not.

With all this, the main question is what is the best way to save user inputs, with orientation changes and back button, and where to restore what was saved.

Thank you!


Solution

  • Check if input values are empty in onBackPressed() and onClick of whatever button that takes the user to Home and display appropriate Toast message