We are facing an issue with android SharedPreferences in our application. Our application is a cordova application. We are storing few data in the SharedPreferences. For example, storing userid, last visited page html contents, few json values.
Following are code samples for managing sharedpreferences (get/set/remove).
//get
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(cordova.getActivity());
Object obj = sharedPrefs.getAll().get(key);
//remove
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(cordova.getActivity());
if (sharedPrefs.contains(key)) {
Editor editor = sharedPrefs.edit();
editor.remove(key);
}
//store
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(cordova.getActivity());
Editor editor = sharedPrefs.edit();
editor.putString(key, value);
editor.commit();
The storing retrieving deleting everything working fine. The problem we are facing is, the data is not persisting in a consistent manner.
For example, user opens the app and then he force close the app, again takes the app. All data in the sharedpreference is persists. But when he force close 2nd time and come back to the app once again, then the data from the sharedpreference is deleted. I could not find any log in the logcat also. Any help will be much appreciated.
Related
I'm doing a quiz where the user unlocked the levels, but when he closes the app all progress is lost, and he has to redo everything again. How can I fix this and make the user's progress automatically saved? Or with it by clicking a button, I do not know
You can save it in SharedPreferences and check the value of it every time application is opened.
To save value:
SharedPreferences sp = getSharedPreferences("YourFileName", Context.MODE_PRIVATE); //YourFileName= Any file name you give it
SharedPreferences.Editor editor = sp.edit();
editor.putString("levels", your_level_value); //levels=key at which data is stored, your_level_value=No. of levels completed
editor.apply();
To retrieve value:
SharedPreferences sp = getSharedPreferences("YourFileName", Context.MODE_PRIVATE); //YourFileName= Any file name you give it
String levelCompleted = sp.getString("levels", "0"); //levels=key at which no. of levels is saved.
The app I am developing should know if the user/android* has cleared cache or clear data , so that I logout the user. How to do this? How to find out if user has cleared cache?
Can the android OS clear the cache of an app by itself (without human intervention)?
Use SharedPreference to store value in Application cache
SharedPreference prefs = getSharedPreferences("UserInfo", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
when App started Retrieve data from SharedPreference
SharedPreference prefs = getSharedPreferences("UserInfo", 0);
String username = prefs.getString("username","");
String password = prefs.getString("password","");
if cache is cleared SharedPreference also cleared.so you have to make a condition like if username and password empty means not enter Application.
I am attempting to save a user id using SharedPreferences. Do values saved as SharePreferences persist across all Activities in my application so I can access the userid from any application? Below is my code for saving the userid.
userid = result.substring(3, result.length());
Log.d("userid at onpostexecute", userid);
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); // to update userid
editor.putString("userid", userid);
editor.commit();
And here is the code for accessing the userid from the SharedPreferences in another activity.
SharedPreferences prefs = getPreferences(MODE_PRIVATE); // to access userid
String userid = prefs.getString("userid", "");
Log.d("shared prefs userid", userid);
What is strange is that the above code is in my onCreate method but it doesn't show up in the Logcat even though other log data is displayed before and after this code. So is there something wrong with my code that I can't even get it to display in my logcat? I can't even tell if it is being updated.
Values saved as sharedPreferences can be shared between activities if you tell it to. Right now you are creating a preference that is only accessible to that same activity. You need to use:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
Like this you are creating a sharedPreference between your application. There is a lot of explanation on the topic in the accepted answer to another question. Link to question
As discussed in the answer the way you are using to save the preference will only work in the same activity that saved it.
I assume you mean can you access them from any Activity, yes, they do persist even when you leave your app and come back. From the Docs
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
If this Log.d("userid at onpostexecute", userid); doesn't even show up then I would put a breakpoint there and make sure you have a value for userid. I would also check your logcat filters to make sure that you are getting all logs. Just make sure that the type in the spinner is set to "verbose" just to be sure
I have a strange problem and I havent been able to find a solution to it.
My SharedPreferences are dissapearing after a few minutes I create a shared preference editor and then commit every change I make. I then get the SharedPreferences values to use using:
settings = getSharedPreferences("settings", 0);
if(settings.contains("accesstoken")){
// create a string that stores the accesstoken from our settings.
String str_access = settings.getString("accesstoken", null);
if(accesstoken_file_data != null){
str_access = accesstoken_file_data;
}
After a while the access token I stored along with all other data stored in SharedPreferences doesn't appear to exist... Thats if I leave my phone for a few minutes. I am developing with a HTC One X.
I am using this method to add values:
String accesstoken = "someVal";
SharedPreferences.Editor editor = settings.edit();
editor.putString("accesstoken", accesstoken);
editor.commit();
I have not found any viable solutions to this yet... if someone could help or direct me that would be great thanks...
SharedPreferences have an unfortunate tendency to wipe its data if the app crashes or is force stopped-
And all saving methods (with the exception of external storage) are wiped if the app data is cleared from settings
You could try to use a different saving method for storing the data. You have databases (SQLite), internal and external storage. The last two are file-based.
On my app I've got a Database which i have to fill one time with some entries. I have packed this step in my splashscreen. Now I got the problem every time i open up my application it puts again all entries to my database.
I'm looking for a way to let this happen only on the really first time the app gets opend. But i don't find out, how i can realize this.
I'm happy over every input and Idea!
Have a nice day
safari
Notes
I had an idea to realize that. I make a boolean in my SplashScreen, which takes a look at the database table if there is nothin, it inputs all the entries and makes a mark in a table that its filled like yes.
Afterwards if i open the app again it takes a look at the database if theres a yes or what ever i definied, it doesn't put again all entries in my database.
Sorry for that crappy definition of what my idea is, my english isnt the best.
I'm searching for an easier way than this.
why not have a startup activity that checks if the app is launched for the first time ( and stores the value in the app preferences ) and either forwards to the database setup activity or to the main activity....
Here's a sample on how to read and write to the preferences:
Define preference key:
public static final String KEY_APP_IS_INITIALIZED = "APP_INITIALIZED";
read boolean value from preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context)
boolean appIsInitialized = prefs.getBoolean(KEY_APP_IS_INITIALIZED, false);
store boolean value to preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context)
Editor editor = prefs.edit();
editor.putBoolean(KEY_APP_IS_INITIALIZED, true);
editor.commit();
Launching the activities:
Intent intent = new Intent(startup_activity,
db_initialized ?
MainActivity.class :
DbInitActivity.class);
startup_activity.startActivity(intent);
You could use SharedPreferences to store a boolean value which indicates if the database is already filled.
You can store the data using this code:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(key, value);
editor.commit();
and then when you start the application you just read your value using:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
pref.getBoolean(value, false);
// Check if DB is set up on start
SharedPreferences settings = getSharedPreferences("yourappidentifiername",MODE_PRIVATE);
String DbSetUp = settings.getString("dbsetup", "no");
// DbSetUp is "no" or "yes"
// Set that DB is set up
SharedPreferences settings = getSharedPreferences("yourappidentifiername",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("dbsetup", "yes");
editor.commit();
Not an optimal solution, but you could check for one of your entries, if they don't exist, add them to your DB, otherwise ignore them.
Try this....
Have one bool value in shared preferences.
Check that variable is set or not on each start of the application.
if not set then set it and perform db operation.
if set don't do db operation just go to next steps.
I've got an idea, reading other answers.
Use a version for the database to write in the sharedpreference, so next time you'll need to update the database, just delete the old one and refill the new one with you data.
public void populateResDB(int version){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int resDbVersion = prefs.getInt("ResDBVersion", 1);
if(resDbVersion<version){
//Populate database here
//Delete table/db
//Populate the table/database with new or updated data
//Update ResDBVersion for the next time
Editor editor = prefs.edit();
editor.putInt("ResDBVersion", version);
editor.commit();
}else{
//installed db has the same version as the one we want to install
//so, do nothing.
}
}
I'm trying it now, not yet tested.
In the onCreate of the splash activity use:
populateResDB(1); //1 is for the first time, increase it manually
You can use method onCreate in your database helper - it's used only, when new database is created, so I think that is what you're looking for.