Android Shared preferences for creating one time activity (example)
Setting values in Preference:
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
More info:
Using Shared Preferences
Shared Preferences
How to use shared preferences across multiple activities?
You can use Singleton pattern to implement global access to the SharedPreferences. Something like this:
public class SharedPreferencesManager {
private static final String APP_PREFS = "AppPrefsFile";
private static final String KEY_FOR_SOMETHING = "KEY_FOR_SOMETHING";
private SharedPreferences sharedPrefs;
private static SharedPreferencesManager instance;
private SharedPreferencesManager(Context context) {
sharedPrefs =
context.getApplicationContext().getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
}
public static synchronized SharedPreferencesManager getInstance(Context context){
if(instance == null)
instance = new SharedPreferencesManager(context);
return instance;
}
public void setSomething(String something) {
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(KEY_FOR_SOMETHING, something);
editor.apply();
}
public String getSomeKey() {
String someValue = sharedPrefs.getString(KEY_FOR_SOMETHING, null);
return someValue;
}
}
You can have as much as you want methods for getting and setting various values to the SharedPreferences, and it will be accessible through the whole application, just do:
SharedPreferencesManager.getInstance(context).getSomeKey();
How to use SharedPreferences in Android to store, fetch and edit values
To obtain shared preferences, use the following method
In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
Edit==>
I noticed, it is important to write difference between commit()
and apply()
here as well.
commit()
return true
if value saved successfully otherwise false
. It save values to SharedPreferences synchronously.
apply()
was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.
More detail is here.
Android - How do I get sharedpreferences from another activity?
Use the following functions to add shared preferences and to fetch the saved values from all activities.
public static void setDefaults(String key, String value, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply(); // or editor.commit() in case you want to write data instantly
}
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
How to use shared preferences to save data that get from database?
First of all you have to create SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("YOUR_PREF_NAME", MODE_PRIVATE);
Editor edt = pref.edit();
To add value in preference:
edt.putString("name", name);
edt.putString("email", email);
edt.putString("alamat", alamat);
edt.putString("notelp", notelp);
edt.putString("username",username);
// Save your changes
edt.commit();
Now for getting data from preference:
String name=pref.getString("name", null);
String email=pref.getString("email", null);
String alamat=pref.getString("alamat", null);
String notelp=pref.getString("notelp", null);
String username=pref.getString("username", null);
If you want to clear the preference data:
edt.clear();
edt.commit();
Android One-time Login screen using SharedPreferences
You can take a look at Android User info and Sign in :
https://developer.android.com/training/sign-in/index.html
Or you can use login with Facebook API.
Otherwise, I would use Shared prefs.
Create a shared prefs file
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
This will create a private file for the current activity. You can use MODE_WORLD_READABLE and MODE_WORLD_WRITABLE if it fits your needs.
You can also provide a file name as the first parameter if needed :
SharedPreferences sharedPreferences = getPreferences("com.example.stackoverflow.myfile", Context.MODE_PRIVATE);
Write a shared pref
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("USERNAME", "test");
editor.commit();
You can put any primitive type : int, string, boolean, etc.
It is a key/value set. the key string "USERNAME" will then have a value of "test".
Read shared pref
String username = sharedPreferences.getString("USERNAME", "NO NAME");
The second parameter is a default value to use if the key "USERNAME" didn't get any value.
Related Topics
How to Avoid Keyboard Pushing Layout Up on Android React-Native
How to Center the Elements in Constraintlayout
Scrollview Not Scrolling in Android Bottomsheet
Check If Json Object Contains Specific Value
How to Get the Currently Displayed Fragment
How to Figure Out Which Sim Received Sms in Dual Sim Android Device
Onclick() to Change Button Border Color Rather Changing Button Color
Remove Span Tag With Text from String
Touchableopacity Not Working Inside an Absolute Positioned View
Force Override Camera Image on Android
Converting Edittext to Int - Android
How to Make Image Fill Relativelayout Background Without Stretching
Adb Error (Error: Protocol Fault (Couldn't Read Status): Invalid Argument)
Android Adb Devices Does Not Detect My Phone
How to Automatically Open App When Receive Push Notification