Save App Settings

Asked

Viewed 369 times

1

There is something I can do to save my application settings without creating a database, so when the application is closed and then reopened it will continue with the settings that were previously recorded?

  • If one of the answers solved your problem, you can choose the one that best solved it and accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem.

2 answers

5


Here’s what you need: https://developer.android.com/guide/topics/data/data-storage?hl=pt-BR

To obtain an object SharedPreferences for the application, use one of these two methods:

  • getSharedPreferences() - use this method if you need several preference files, identified by name and specified in first parameter.
  • getPreferences() - use this method if you only need one file preferably for Activity. As this will be the only preferences for Activity, the name is not provided.

To save values:

  • Call edit() to get a Sharedpreferences.Editor.
  • Add values with methods like putBoolean() and putString().
  • Confirm the new values with commit()

To read values, use SharedPreferences as getBoolean() and getString().

Example:

public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean silent = settings.getBoolean("silentMode", false);
       setSilent(silent);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
    }
}

2

The simplest, in my opinion, is java.util.prefs.Preferences (documentation) which comes along with Java. Use normally to save position and size of windows, directory used to open files, ....

Get instance (member of each class):

// chaves para acessar cada dado
private static final String PREF_TEXTO = "ChaveTexto";
private static final String PREF_INTEIRO = "ChaveInteiro";

private final Preferences preferences = Preferences.userNodeForPackage(getClass());

Save:

preferences.put(PREF_TEXTO, texto);
preferences.putInt(PREF_INTEIRO, numero);

Reclaim:

texto = prefrences.get(PREF_TEXTO, "valoe inicial");
numero = preferences.getInt(PREF_INTEIRO, 0);

Beyond the userNode, which applies to a particular user, there is the systemNode that goes for all users.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.