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 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.
How Shared Preferences in Android Works?
The SharedPreference object does not print anything.
The sharedPreference stores data in key-value pairs in an xml file named MyPref in your case:
getApplicationContext().getSharedPreferences("MyPref", 0);
You put the value you want to store by calling the putXX method on the editor object obtained from the pref object by calling edit() on it:
SharedPreferences.Editor editor = pref.edit();
** putXX means put[some kind of primitive data] like int float String.
When you call putString you supply a key as the first parameter and the String value in this case as the second parameter:
editor.putString("1", "2"); // Storing string
editor.putInt("myInt", 2); // Storing integer
The commit method writes the data.
editor.commit();
The getString retrieve a string value for a key given as the first parameter and if they are no entry a default value returned which is the second parameter in this case "3":
String myValue = pref.getString("2","3")
The printing performed by calling:
System.out.println(myValue);
Reading shared preferences
On code behind;
SharedPreferences prefs = this.getSharedPreferences("general_settings", Context.MODE_PRIVATE);
String lanSettings = prefs.getString("language", null);
How can I know that Android SharedPreferences are saved successfully?
From the docs.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Then go and check commit()
method here.
Return type: boolean
Description: Returns true if the new values were successfully written to persistent storage.
Use shared Preference values in Repository or ViewModel of Android
public class FoodieViewModel extends AndroidViewModel {
........
SharedPreferences sharedpreferences =getApplication().getSharedPreferences("preference_key", Context.MODE_PRIVATE);
...........
//wherever u want to get token
String token = sharedpreferences.getString("token", "")
}
android shared preference is null
You are saving the preference in one Activity say A, And accessing in another activity say B, and context of both activities are different and so preferences values cannot be accessed as mode is private.
try
this.getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Edit and save shared preferences in Android Studio
I can access shared preferences in Android Studio from Device file explorer, but after editing the file, the changed values aren't saved. How can I save the changes?
You're not editing the files directly. When you open a file that's on the device, Android Studio is actually pulling a copy to your local machine.
For example, if I selected this random i_log
file from my SDCard it ends up here on my local machine under Documents
on Mac (shown in the top status bar in Android Studio).
If you want to save the changes back to the device, you need to "upload" the file back to the device.
- On the folder in the device explorer you want to move the file to, right-click.
- Select Upload..
- In the file chooser dialog, navigate to the local copy you edited.
AS will push that file back to the device.
Related Topics
How to Get Pixel Color in Android
Android Drawing Separator/Divider Line in Layout
Generate Sha-1 for Flutter/React-Native/Android-Native App
Android Update Activity UI from Service
Self-Signed Ssl Acceptance on Android
How to Disable Bottomnavigationview Shift Mode
How to Make Wrap_Content Work on a Recyclerview
How to Refresh Mediastore on Android
How to Open the "Front Camera" on the Android Platform
Android - Cancel Asynctask Forcefully
Error:Execution Failed for Task ':App:Transformclasseswithdexfordebug'
What Does "Program Type Already Present" Mean
Proper Implementation of Viewpager2 in Android
Android API 21 Toolbar Padding