Android not saving sharedPrefs [duplicate] - android

This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 7 years ago.
So I'm just trying to save a string.. But everytime I rerun the app, I get null for the saved String :/ I'm 100% sure I'm calling the save method, and that the string it not null when I'm saving it.
public class CFUser {
private final static String ID_KEY="myUserID";
private static String userID;
public static String getUserID(Context context) {
if(userID==null) {
SharedPreferences prefs= context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
userID=prefs.getString(ID_KEY, null);
}
return userID;
}
public static void setUserID(String id, Context context) {
userID=id;
Log.d("saving", id);
SharedPreferences prefs=context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
prefs.edit().putString(ID_KEY, userID);
prefs.edit().apply();
}
public static boolean isLoggedIn(Context context) {
return getUserID(context)!=null;
}
}
many thanks!

In this code, you are creating two different SharedPreferences.Editor Objects:
SharedPreferences prefs=context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
prefs.edit().putString(ID_KEY, userID);
prefs.edit().apply();
So that means you are putting the String in Editor1, but are committing the (non-existant) changes of Editor2.
You need to do it this way:
SharedPreferences prefs=context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
SharedPreferenced.Editor edit = prefs.edit();
edit.putString(ID_KEY, userID);
edit.apply();

At the moment the name of your entire SharedPreferences file is myUserID because of how you're retrieving the SharedPreferences. Instead use the following. This isn't causing the issue but I'm assuming you don't want the SharedPreferences file as your ID key...
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Then when you're writing to the preferences make sure you're using the same Editor.
Editor editor = preferences.edit();
editor.putString(ID_KEY,userID);
editor.apply();

Related

Mess with the shared preferences of android - which function to use?

Here's a standard task: store some values in the application's shared preferences in order to be able to retrieve it later on.
But one will discover that there are 3 functions to store a value in there:
//1.
public static SharedPreferences PreferenceManager.getDefaultSharedPreferences(Context context) {}
//2.
public SharedPreferences Activity.getPreferences(int mode) {}
//3.
public SharedPreferences ContextWrapper.getSharedPreferences(String name, int mode) {}
So now here's the question: which one to choose and which one is better or there's a different purpose for each of them?
Here's the answer to my own question:
First, let's take a look at the implementations of those 3 functions.
//1.
public static SharedPreferences PreferenceManager.getDefaultSharedPreferences(Context context) {
return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());
}
//2.
public SharedPreferences Activity.getPreferences(int mode) {
return getSharedPreferences(getLocalClassName(), mode);
}
//3.
public SharedPreferences ContextWrapper.getSharedPreferences(String name, int mode) {
return mBase.getSharedPreferences(name, mode);
}
Here mBase is a reference to an object of type Context.
We see that the 2nd functions calls the 3rd one, and all those 3 functions are basically equivalent but with different parameters. Think of overloading.
Next, going deeper to the 1st function's implementation, we can simplify its call as the following:
//1.
public static SharedPreferences PreferenceManager.getDefaultSharedPreferences(Context context) {
return context.getSharedPreferences(context.getPackageName() +
"_preferences", Context.MODE_PRIVATE);
}
and similarly, for the second function:
//2.
public SharedPreferences Activity.getPreferences(int mode) {
return mBase.getSharedPreferences(getLocalClassName(), mode);
}
To sum-up, the 1st function creates a shared preference file with a name as <your_package_name>_preferences, the 2nd function creates a shared preference file with a name as <your_class_name>, and finally, the 3rd function lets you to specify arbitrary name for the shared preference file.
Needless to say that you need to specify the correct name for the shared preference file in order to retrieve the saved values back. So you may use the 3rd function to specify the name yourself or to use the 1st or 2nd function respective to how you have saved it before.
Warning! Make sure you are passing the correct instance of the Context class.
For example, a messy scenario would look like this: you are saving into shared preferences from a background thread which is running in the system (like for example when using the android's out-of-the-box SyncAdapter framework) and trying to get back the saved values from your UI-thread, you may get the default/wrong values!
Hope this will be helpful for someone else... ;)
I am sharing mine, hope it will make life easy -
public class SharedPreferenceStore {
public static void deleteValue(Context context, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = preferences.edit();
editor.remove(key).apply();
}
public static void storeValue(Context context, String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = preferences.edit();
editor.putString(key, value).apply();
}
public static void storeValue(Context context, String key, boolean value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = preferences.edit();
editor.putBoolean(key, value).apply();
}
public static void storeValue(Context context, String key, double value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String doubleVal = String.valueOf(value);
Editor editor = preferences.edit();
editor.putString(key, doubleVal).apply();
}
public static void storeValue(Context context, String key, float value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = preferences.edit();
editor.putFloat(key, value).apply();
}
public static void storeValue(Context context, String key, long value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = preferences.edit();
editor.putLong(key, value).apply();
}
public static void storeValue(Context context, String key, int value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = preferences.edit();
editor.putInt(key, value).apply();
}
/*************************
* GET Methods
***************************************/
public static String getValue(Context context, String key, String defValue) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, defValue);
}
public static boolean getValue(Context context, String key, boolean defValue) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(key, defValue);
}
public static double getValue(Context context, String key, double defValue) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String doubleVal = String.valueOf(defValue);
return Double.parseDouble(preferences.getString(key, doubleVal));
}
public static float getValue(Context context, String key, float defValue) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getFloat(key, defValue);
}
public static long getValue(Context context, String key, long defValue) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getLong(key, defValue);
}
public static int getValue(Context context, String key, int defValue) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getInt(key, defValue);
}
}
Just use the class and forget about all complications of SharedPrefences. Hope it will help you :)
its one and only method, just different calls and accesibility
"default" means you are not declaring name of XML file storing your data (thats the way that SharedPreferences work) and it will be available from every Activity/Context (lets say "globally") - if you want to keep ony few values you may use this
is keeping values available only for calling Acivity - "private" for storing Activity, but be aware about int mode
the last one is working also "globally" like first one, but in here
you may declare file name and keep few files with different kinds of
values - dedicated for creating more complicated storing values constructions (some wrappers etc.)
It depends. #1 Will return the SharedPreferences for whichever Context you pass it. #2 Will return the SharedPreferences for the context of the Activity you're in. This may be the same as #1 or it might not. #3 Will let you break your SharedPreferences up into different groups and name them. This might be a nice way to break things up but I have never actually done it.

Shared Preference fetching previous URL in android

I'm trying to save my URL using Shared Preference and the URL keeps changing for every second. Now my problem is when I try to fetch the URL with the Shared Preference variable, it is fetching previously saved URL and not the current URL and also when I run my app for first time it is showing blank but second time it is showing the URL that should have come first time.
This is my code.
SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
editor.putString("name", url);
editor.commit();
And to retrive the URL I wrote it in this way.
SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
String name=preferences.getString("name","not loaded");
What should I do ?
MODE_MULTI_PROCESS was there to refresh data from disk every time. Because multiple processes could be modifying preferences data and data loaded in memory for one process wouldn't have changes from other process. It has been deprecated for not working reliably.
As far as your particular problem, I'd recommend something like:
public class PrefStore {
private static final String PREF_NAME = "app_prefs";
private final SharedPreferences mPreferences;
public static final String KEY_URL = "key_url";
public PrefStore(Context context) {
mPreferences = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
}
public void saveUrl(String url){
mPreferences.edit().putString(KEY_URL,url).apply();
Log.i("PREF_TEST",String.format("Write URL:%s at:%s by thread:%s",url, new Date(), Thread.currentThread().getId()));
}
public String getUrl(){
String url = mPreferences.getString(KEY_URL,null);
Log.i("PREF_TEST",String.format("READ URL:%s at:%s by thread:%s",url, new Date(), Thread.currentThread().getId()));
return url;
}
}
Log will help you inspect whether its a timing/thread problem.

How to use Android SharedPreferences

I am working on an Android project where a user can store some data but is able to delete and change/alter/update the values, I have been searching for a while now for a tutorial, but are not able to find any, so I was wondering, Is it possible to use SharedPreferences for that?
While you can always read the docs and know more about SharedPreferences, for a quick start here are few static methods from one of my project which you can use.
public static boolean getBooleanPrefs(Context ctx, String key) {
return PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean(key, false);
}
public static void setBooleanPrefs(Context ctx, String key, Boolean value) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().putBoolean(key, value).commit();
}
public static String getStringPrefs(Context ctx, String key) {
return PreferenceManager.getDefaultSharedPreferences(ctx).getString(key, "");
}
public static void setStringPrefs(Context ctx, String key, String value) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().putString(key, value).commit();
}
public static int getIntPrefs(Context ctx, String key) {
return PreferenceManager.getDefaultSharedPreferences(ctx).getInt(key, 0);
}
public static void setIntPrefs(Context ctx, String key, int value) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().putInt(key, value).commit();
}
public static void clearPrefs(Context ctx) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().clear().commit();
}
So far if data is limited to some values, yes you can use SharedPreferences for that. You can easily update/alter/clear values in SharedPreferences.For usage of Shared preferences, refer these
Android Shared preferences example
http://developer.android.com/guide/topics/data/data-storage.html#pref
http://www.tutorialspoint.com/android/android_shared_preferences.htm
But if your data is not limited and have some repititive type of values to be stored.For eg. data of app users, their info and all that, then you should go for local database using SQLite. For SQLite,you should go through this tutorial
For pros and cons of SQLite and SharedPreferences, you should go through this answer
shared preference is good way to store values.
need to declare shared preference and stored value to it like.
SharedPreferences prefrs = PreferenceManager
.getDefaultSharedPreferences(getApplication());
Editor editor = prefrs.edit();
editor.putString("key",abc);
editor.commit();
you can easily get that value like below...
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String name = prefs.getString("key", "default");
you can delete that stored value and can use for stored new value like below
SharedPreferences prefrs = PreferenceManager
.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editor = prefrs.edit();
editor.clear();
editor.commit();
finish();

Android : How to store a generated ID and recall it the next app run?

Every time my app starts an ID is generated by my program. Since each time it generates a different ID , I want to save the ID somewhere before exiting the program so I can use it again when the program runs later.
Sample ID : 125469
Note : I rather to not save it in file but some else.
Even a better solution would be to use GreenDAO here are some examples
https://github.com/greenrobot/greenDAO
https://github.com/octa-george/Android-GreenDao-Sample
GreenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases. Being highly optimized for Android, greenDAO offers great performance and consumes minimal memory.
You only need the greendao jar
public class MyDaoGenerator {
public static void main(String args[]) throws Exception {
Schema schema = new Schema(1, "ro.octa.greendaosample.dao");
createSchema(schema);
new DaoGenerator().generateAll(schema, "C:/GreenDaoSchema");
}
private static void createSchema(Schema schema) {
Entity user = schema.addEntity("DBUser");
user.addIdProperty().primaryKey().autoincrement();
user.addStringProperty("email").notNull().unique();
user.addStringProperty("password").notNull();
}
After a few lines of code you have the model generated for autoincrement id, email and password.
You can use SharedPreferences or you can use SQLite database for storing purposes.
You can do it like that:
private SharedPreferences prefs;
...
...
private void initializeFromPreference() {
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
myId = prefs.getInt("myId", myId );
}
...
...
public void onDestroy() {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("myId", myId );
editor.commit();
super.onDestroy();
}
i wouldnt use a database for a single value, Sharedpreferences is a good way to do so
You can Use SharedPreferences to store your id
SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey", Context.MODE_PRIVATE);
Editor edit=prefs.edit();
//to store value
edit.putInt("Your Id Name", Id Value).commit();
//to get value
int id=prefs.getInt("Your Id Name", 0);
Here's the simple way, I can think of :)
public static SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences("MyIds", Context.MODE_PRIVATE);
if (sharedpreferences.contains("id"))
{
String id = sharedpreferences.getString("id", "");
// *Use existing id and enjoy* ;)
}
else{
// *Generate New ID (yourID)*
Editor editor = sharedpreferences.edit();
editor.putString("id", yourID);
editor.commit();
}

SharedPreferences commit and rollback

Is the following the intended/reasonable way to commit and rollback SharedPreferences, and to use it in general?
public class Settings {
private static final String PREFS_NAME = "Settings";
private static SharedPreferences preferences = null;
private static SharedPreferences.Editor editor = null;
public static void init(Context context) {
// Activity or Service what ever starts first provides the Context
if (preferences == null)
// getSharedPreference because getPreferences is a method of Activity only (not Service or Context)
preferences = context.getSharedPreferences(PREFS_NAME, 0);
editor = preferences.edit();
}
public static String getEmail() {
return preferences.getString("email", null);
}
public static void setEmail(String email) {
editor.putString("email", email);
}
public static String getPassword() {
return preferences.getString("password", null);
}
public static void setPassword(String password) {
editor.putString("password", password);
}
public static void save() {
editor.commit();
}
public static void rollback() {
editor = preferences.edit();
}
}
This is more detail as enforced by stackoverflow editor. I really don't know what else should be said about this.
Experts' feedback is much appreciated. And if may snipped is reasonable it could well as better explanation then all other threads I have found here.
There is only one change in the following method from my understanding. Because if u forget to initialize preference ,u will get null pointer exception.
public static void rollback(Context context) {
if (preferences == null)
// getSharedPreference because getPreferences is a method of Activity only (not Service or Context)
preferences = context.getSharedPreferences(PREFS_NAME, 0);
editor = preferences.edit();
}
Best way to have things persisted is "USE OF PREFERENCE ACTIVITY". See examples and read online docs about them. Use EditTextPreference for automatically persisting values.
First thing is that no body ever uses shared preference to save user id and password . Because shared preference is key-value pair. For key Email you can have only one respective value. Here what you want is :- for key Email multiple values and for key password also multiple value.
There exist one solution if u want to do something like this. Use email id (xyz#xyz.com) as key . And password as the value of key(xyz#xyz.com).

Categories

Resources