I want to save a flag for recognizing that my app is run for the first time or not. For this simple job I don't want to create database..
Is there a simple option to do this? I want to save and read little pieces of information only.
Use sharedPreference
or files
to save the data but better option is sharedPreference
.
For Retrieving
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
For Saving
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", true);
editor.commit();
Use SharedPreferences
.
SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
SharedPreferences.Editor edit= preferences.edit();
edit.putBoolean("isFirstRun", false);
edit.commit();
A proper way to do this is by using the Android class SharedPreferences
which is used for things like this.
SharedPreferences settings = getSharedPreferences(NAME_OF_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("appPreviouslyStarted", true);
editor.apply();
Don't forget to apply or your mutations to the settings won't be saved!
You can create multiple settings by using different NAME_OF_PREFERENCES
. The settings are stored on the device so will be available after closing the application.
When you try to retrieve NAME_OF_PREFERENCES
that is not already created, you create a new one. See more behavior like this here.
You can use editor.apply()
as well as editor.commit()
, the only difference is that apply() does not return a boolean
value with if the edit was successful or not. editor.apply() is therefor faster and more commonly used.
You can see all about the different modes here. For your case MODE_PRIVATE
is fine.
SharedPreferences settings = getSharedPreferences(NAME_OF_PREFERENCES, MODE_PRIVATE);
boolean silent = settings.getBoolean("silentMode", false);
When retrieving a settings from a SharedPreferences
object you always have to specify a default value which will be returned when the setting was not found. In this case that's false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With