how to use getSharedPreferences in android
First get the instance of SharedPreferences using
SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
Now to save the values in the SharedPreferences
Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();
Above lines will write username and password to preference
Now to to retrieve saved values from preference, you can follow below lines of code
String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");
(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)
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.
getSharedPreferences in android does not work
getSharedPreferences()
is a method in the class Context
. Call it on your context object:
SharedPreferences shared = context.getSharedPreferences("Prefs", MODE_PRIVATE);
Why it works e.g. in an activity is because Activity
is-a Context
.
Android - How to use SharedPreferences in non-Activity class?
SharedPreferences are related to context.
You can only reference it through a context.
You can simply pass context as a parameter to your class.
For example in the constructor.
In your activity do:
MyClass myClass = new MyClass(this);
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 getSharedPreferences in Fragment?
Have you tried getActivity().getSharedPreferences(...)?
Edit:
Possible duplicate of Android SharedPreferences in Fragment
How to getSharedPreferences in Application?
Override onCreate()
, in your app,
@Override
public void onCreate() {
super.onCreate();
and do it there. Don't forget to declare your Application
subclass in the AndroidManifest
as well. E.g.
<application
android:name="App"
Android non-Activity getSharedPreferences
One way is to use Application object. This is a dirty hack but none the less sometimes helpful.
First you need a static member in your Application class, so:
public class MyApplication extends Application {
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static MyApplication getInstance() {
return instance;
}
}
Since Application object is always created before any activity is created and run and is kept throughout application lifetime you can always be sure you will have proper one.
Then in your code simply call MyApplication.getInstance()
and you will have global app context.
Remember to declare MyApplication
in manifest.
Android SharedPreferences in Fragment
The method getSharedPreferences
is a method of the Context
object, so just calling getSharedPreferences from a Fragment
will not work...because it is not a Context! (Activity is an extension of Context, so we can call getSharedPreferences from it).
So you have to get your applications Context by
// this = your fragment
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
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()
Related Topics
Actionbar Logo Centered and Action Items on Sides
Simulate Low Battery & Low Memory in Android
Get List of Installed Android Applications
Replace Default Android Maps API V2 Change Mylocation Icon
"Id Cannot Be Resolved or Is Not a Field" Error
Volley Android Networking Library
How to Receive Serial Data Using Android Bluetooth
Modifying Camera Output Using Surfacetexture and Opengl
Android, How to Not Destroy the Activity When I Rotate the Device
Expandablelistview - Hide Indicator for Groups with No Children
Detect When Recyclerview Reaches the Bottom Most Position While Scrolling
How to Use View.Ontouchlistener Instead of Onclick
Appcompatactivity.Oncreate Can Only Be Called from Within the Same Library Group
Problems with Gridview Inside Scrollview in Android
Android - Acceleration Down (Smash)