Domanda

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!

È stato utile?

Soluzione

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

Altri suggerimenti

Add android:configChanges="orientation"to manifest file. Override onConfigurationChanged. Before you call super.onConfigurationChanged save the data. If you have different layout files for portrait and landscape you have to remove all the views and setcontentview and initialize them(just like what you do on create ) after all these you can restore the data

I don't quite follow your logic. Lets see ... You have two edittext fields and save button, when user changes screen orientation on destroy you can save input in shared preferences or in Bundle and when onCreate() starts you can check if values are not empty and then show toast that there is a draft. If user hits back button you can also save input and display toast, if he/she hits send you just send input, right ?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top