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 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 to save and read from a Class
Here Maybe this help
Its a good practice making separate class file for shared prefrence
first, create a file(class) name Constants.java
public class Constants {
static Constants _instance;
Context context;
SharedPreferences sharedPref;
SharedPreferences.Editor sharedPrefEditor;
public static Constants instance(Context context) {
if (_instance == null) {
_instance = new Constants();
_instance.configSessionUtils(context);
}
return _instance;
}
public static Constants instance() {
return _instance;
}
public void configSessionUtils(Context context) {
this.context = context;
sharedPref = context.getSharedPreferences("AppPreferences", Activity.MODE_PRIVATE);
sharedPrefEditor = sharedPref.edit();
}
public void storeValueString(String key, String value) {
sharedPrefEditor.putString(key, value);
sharedPrefEditor.commit();
}
public String fetchValueString(String key) {
return sharedPref.getString(key, null);
}
}
The above code will generate an XML file inside your phone with the name AppPreferences
where you can store value in key-value pair
Now go to an activity where you want to access shared preference
Constants.instance(this.getApplicationContext());
Now when you want to store inside shared preference use like that
Constants.instance().storeValueString("companyKey", "Brainwash Inc.");
now when you want to fetch data from shared prefrence
String companyName = (Constants.instance().fetchValueString("companyKey"));
Note Its for Activity if you want to use inside fragments use getactivity() instead of getapplicationcontext()
Safest way to use SharedPreferences
Type 1:-
In the type 1, You directly use this class method
, this one is best........
Type 2:-
In the type 2, there is one Static Variable
that will cause the MemoryLeakException
in your application. If you wanted to use the type 2 then, you have made INSTANCE
variable null whenever you use this class (these can solve the problem of MemoryLeakException
).......
Type 3:-
In type 3, You have to create Heap Memory
(take Ram memory for Instance until its scope end) Or new Instance
of class, whenever you want to use this class. This class will help if you have to use this class methods
in many time in single Activity
.......
use this class for simple use of
SharePrefernce
.....
public class Utility {
public static boolean getBoolean(Context context, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(key, false);
}
public static String getString(Context context, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, "");
}
public static int getInt(Context context, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getInt(key, -1);
}
public static void setString(Context context, String key, String value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).commit();
}
public static void setBoolean(Context context, String key, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(key, value).commit();
}
}
for setting string ....
Utility.setString(this,"token","your token");
and for getting string ...
Utility.getString(this,"token");
Note : - In this clas, you don't have to create any Heap Memory OR Static Variable.
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", "")
}
How to use shared preferences to keep user logged in flutter?
You can navigate to the Login
page if the user details are saved in the storage else to the Home
page with the below code
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
var email = prefs.getString('email');
print(email);
runApp(MaterialApp(home: email == null ? Login() : Home()));
}
Save the required user details after the successful login
class Login extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () async {
//after the login REST api call && response code ==200
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('email', 'useremail@gmail.com');
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (BuildContext ctx) => Home()));
},
child: Text('Login'),
),
),
);
}
}
clear the details on logout
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Center(
child: RaisedButton(
onPressed: () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove('email');
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (BuildContext ctx) => Login()));
},
child: Text('Logout'),
),
),
);
}
}
Hope it helps!
what is the Best way to use shared preferences between activities
Sending shared preferences through intents seems overcomplicated. You could wrap the shared preferences with something like the below and call the methods directly from your activities:
public class Prefs {
private static String MY_STRING_PREF = "mystringpref";
private static String MY_INT_PREF = "myintpref";
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences("myprefs", 0);
}
public static String getMyStringPref(Context context) {
return getPrefs(context).getString(MY_STRING_PREF, "default");
}
public static int getMyIntPref(Context context) {
return getPrefs(context).getInt(MY_INT_PREF, 42);
}
public static void setMyStringPref(Context context, String value) {
// perform validation etc..
getPrefs(context).edit().putString(MY_STRING_PREF, value).commit();
}
public static void setMyIntPref(Context context, int value) {
// perform validation etc..
getPrefs(context).edit().putInt(MY_INT_PREF, value).commit();
}
}
How to use shared Preference values in Viewmodel
Your ViewModel class should be extend by AndroidViewModel.
after that call getApplication() and use it as context when accessing SharedPreferences.
public class YourViewModel extends AndroidViewModel {
SharedPreferences sharedpreferences = getApplication().getSharedPreferences("pref_key", Context.MODE_PRIVATE);
String varName = sharedpreferences.getString("var_name", "")
}
Related Topics
Cardview Layout_Width="Match_Parent" Does Not Match Parent Recyclerview Width
Android - Extracting Cookies After Login in Webview
How to Display Image in Android's Textview
How to Move the Layout Up When the Soft Keyboard Is Shown Android
How to Take Camera Capture Without a Preview from a Service or Thread
Android - Get Time of Chronometer Widget
Android Material: Status Bar Color Won't Change
How to Draw a Route, Along an Existing Road, Between Two Points
Android Speech Recognition Continuous Service
How to Resolve "Waiting for Debugger" Message
How to Set Android_Sdk_Home Environment Variable
Error :: Duplicate Files During Packaging of APK
Android Background Image Memory Usage
Actionbar Logo Centered and Action Items on Sides
Adding Opencv to Native C Code Through Cmake on Android Studio