Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save little information as setting in android (like first time that app is run)

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.

like image 521
Fcoder Avatar asked Mar 13 '13 12:03

Fcoder


3 Answers

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();
like image 145
Ajay S Avatar answered Nov 15 '22 04:11

Ajay S


Use SharedPreferences.

SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
SharedPreferences.Editor edit= preferences.edit();

edit.putBoolean("isFirstRun", false);
edit.commit();
like image 33
Rajitha Siriwardena Avatar answered Nov 15 '22 04:11

Rajitha Siriwardena


A proper way to do this is by using the Android class SharedPreferences which is used for things like this.

Storing Settings

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.

apply() versus commit()

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.

What is MODE_PRIVATE

You can see all about the different modes here. For your case MODE_PRIVATE is fine.

Retrieving settings

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.

like image 29
Joop Avatar answered Nov 15 '22 06:11

Joop