SharedPreference not available after app restart - android

I'm trying to figure out why I can't have access to my SharedPreference file after an app restart.
In my Application class in the onCreate I define my SharedPreference once :
pref = getSharedPreferences(Util.PREF_FILE_NAME, Context.MODE_PRIVATE);
editor = pref.edit();
And then in the onResume of my activity I call:
String userName = MyApp.getApplication().pref.getString(Util.USER_NAME, "");
But at this point the user name is always empty after a restart.
-To save my value :
MyApp.getApplication().editor.putString(Util.USER_NAME,"name").commit();
-For MyApp.getApplication() I've defined in my Application class:
public MyApp() {
instance = this;
}
public static MyApp getApplication() {
if (instance == null) {
instance = new MyApp();
}
return instance;
}
From my device I run a terminal app and with a 'cat' command I can see the content of my sharedPreference XML file. Even when I kill my app I can see the sharedPreference file is still there with my correct value inside.
But when I restart my app this value can't be read. What is happening there ?
I've noticed on a tablet with android Lollipop I've no problem but with a tablet with android Kitkat I have this problem.

Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
So Dont forget to your editor.commit()

Best Way which I using :
Util.class
public static void saveIntToUserDefaults(Context c, String Key, int value) {
SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(Key, value);
editor.commit();
Log.e("Saved:", "" + Key + "-" + value);
}
public static String getFromUserDefaults(Context c, String Key) {
SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedpreferences.getString(Key, "");
}
public static void clearUserDefaults(Context c) {
SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.clear();
editor.commit();
}
I calling this wherever I need & its working superb

Related

unable to clear my sharedPreferences using editor.clear().commit();

I am working on an android project where I have a scenario such as :
I used place picker.and data that place picker gave is sent to different activities using shared preference.and show this data in TextView.
but the problem is when I closed activity and again open that activity; my data still visible in TextView.
even when I cleared it in onDestroy().
here is my code for send data :
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("address", (String) Address);
editor.commit();
finish();
here is my code to set and clear data:
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
String n = settings.getString("name", "");
String a = settings.getString("address", "");
name.setText(n);
location.setText(a);
}
#Override
protected void onDestroy() {
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("address");
editor.clear().commit();
super.onDestroy();
}
here is my preference manager class :
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "sara";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.clear().commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
And please don't mark this question as duplicate because I see every related questions and see answers. I tried every possible solutions but nothing worked for me. I am new to android so please help me.
I'm not sure where you are using SharedPreference object to set data in it. But I guess this is the problem:
In this activity, you are clearing SharedPreferenece correctly.
You go back to previous Activity. And the previous activity, sets data to shared preference, again. So SharedPreference is not empty anymore.
You go to second activity (which you remove shared preference data in onDestroy()). As shared preference is not empty, you are seeing data again.
So check the code again and feel free to ask any questions.
Try check the logs to make sure you are really going 'onDestory' well.
#Override
protected void onDestroy() {
Log.d("address", "onDestory");
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("address");
editor.clear().commit();
super.onDestroy();
}
There is no problem with the code for creating and removing SharedPreferences.

Android SharedPref not saving on restart

In my Android app I can display a popup when the app is updated (Based on versionCode). In the popup I have put a checkbox saying "dont show me again". When I click on that, it will save in the sharedpref the versionCode and wont display the popup anymore.
I have run against something odd behaviours where when I have saving the new Set<String>, it did indeed was saving it but when my app restarts the settings is lost.
Set<String> readAnnouncement = getReadAnnouncement(this);
readAnnouncement.add(String.valueOf(versionCode));
PreferenceManager.getDefaultSharedPreferences(this).edit().putStringSet(KEY_READ_ANN, readAnnouncement).apply();
If I break point on readAnnouncement.add, I can set for example the list having 2 items. When I execute the PreferenceManager.getDefaultSharedPrefer... and then execute getReadAnnouncement(this); the value is there, all good.
If I restart the app and check again getReadAnnouncement(this); the new value is gone.
By clearing the cache the problem disappeared... Why was is not saving? Is it possible the SharedPreference were full?
Try like this.
import android.content.Context;
import android.content.SharedPreferences;
/**
* #author VIVEK
* This class deals in with setting Cache value for complete app.
*/
public class SharedPrefUtil{
/*Set Boolean value in shared preferences */
public static void setSharedPref(Context context, String key, boolean value) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
/*get Boolean value in shared preferences */
public static boolean getSharedPref(Context context, String key, boolean defaultVal) {
boolean prefToken = defaultVal;
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
prefToken = sharedPreferences.getBoolean(key, false);
return prefToken;
}
/*Set String value in shared preferences */
public static void setSharedPref(Context context, String key, String value) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
/*get String value in shared preferences */
public static String getSharedPref(Context context, String key, String defaultVal) {
String value = defaultVal;
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
value = sharedPreferences.getString(key, defaultVal);
return value;
}
public static void cleanSharedPrefFile(Context context) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
} // End of main class over here ...
Now you want to set some value in Shared Pref then set like this
SharedPrefUtil.setSharedPref(MainActivity.this, "test", storeBuff);
Now when you need to get value from shared Pref then call like this
SharedPrefUtil.getSharedPref(MainActivity.this, "test", "default value");
In place of editor.commit() , use editor.apply()
BASICS:
getDefaultSharedPreferences() uses a default preference-file name. This default is set per application, so all activities in the same app context can access it easily as in the following example:
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
if (spref.contains("email")) {
String sEmailAddr = spref.getString("email", "");
}
The preferences are usually stored at /data/data/com.package.name/shared_prefs/com.package.name_preferences.xml
The alternative method - getSharedPreferences(name,mode) requires to indicate a specific preference (file) name and an operation mode (e.g. private, world_readable, etc.), which allow to have better access over your SharedPref file.

Not able to clear shred preferences

This is in my main activity class, I can pass and retrieve data in my other class through shared preferences but I cant clear the shared preferences in my other class. Also tell me how to check that my shared preferences are cleared.
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "userKey";
public static final String Pass = "passKey";
sharedPreferences=getApplicationContext().getSharedPreferences(MyPREFERENCES,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name,userName);
editor.putString(Pass,password);
editor.commit();
this is in my other class
SharedPreferences sharedPreferences;
sharedPreferences=getApplicationContext().getSharedPreferences(SignUPActivity.MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
editor.commit();
Hi if you want just pass value from one Activity to Another or One Fragment to other than I suggest you to use INTENT to pass data
Look at this example how to pass -http://startandroid.ru/en/lessons/241-lesson-28-extras-passing-data-using-intent.html
Also -https://stackoverflow.com/a/30166602/4741746
sharedPreferences is used when data used for all activity which is permanatly stored in application you also can clear data
Remove given String from shearedPrefrance
public static void removeFromSharedPreferences(Context mContext, String key) {
if (mContext != null) {
SharedPreferences mSharedPreferences = mContext.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, 0);
if (mSharedPreferences != null)
mSharedPreferences.edit().remove(key).commit();
}
}
Remove All value from SharedPrefrance
public static void removeSharedPreferences(Context mContext) {
if (mContext != null) {
SharedPreferences preferences = mContext.getSharedPreferences("PREFERENCE", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
}
}
And why your code is not working is you have to passs Context.MODE_PRIVATE insted MODE_PRIVATE jsut confirm both should have same value
Put this code in both the classes
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Possible Reason is you are not using the same preferences.
In your first activity you are using:
sharedPreferences = getApplicationContext()
.getSharedPreferences(MyPREFERENCES,MODE_PRIVATE);
And in the other activity you should also use it.
Try to read these
http://developer.android.com/reference/android/app/Activity.html
also from the docs
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity. This simply calls the underlying
getSharedPreferences(String, int) method by passing in this activity's
class name as the preferences name.

How to use SharedPreference to save score and name in a game?

I am creating my first android app and I don’t have enough knowledge in programming unlike other here. So please help me with this matter. I want to save player’s name and score. I’ve searched and read a lot about SharedPreference but was unable to understand it very well especially when I am already applying the codes on my activity. I have tried it twice and everytime I run it, it shows”Not Responding” message and closes. But when the codes for sharedpreference are not indicated there it works fine. So here’s how I want to do with these. On the first game, the very first score should be saved after the time is over (the user will be typing their name and click save). So when another user or player plays the game the Top Score should be indicated in the screen using a textview, below this Top Score textview is the Current Score textview. If the Current Score is greater than the Top Score then it should overwrite the score. If not then the Top Score should stay the same. How can I achieve this?
P.S. I have 3 different activities that needs this SharedPreferences but with the same functionalities. Thanks in advance. And please explain it more clearly (coz sometimes I can’t understand some words) thank you :)
This is the code i use, i put it in Oncreate
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", name);
editor.putInt("score", score);
editor.commit();
I think following link will surely help you out SharedPreferences Explained in detail
.
Try this
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value); //similar way you can push integer values
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sp.getString(key, null); //default value will be null in this case, if there is no such key
You can write a Utility class to reuse this methods wher you want. like below
public class PreferenceUtility {
public static void saveString(Activity activity, String key, String value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static String readString(Activity activity, String key, String defaultValue){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
return sp.getString(key, defaultValue);
}
}
static SharedPreferences sh_Pref;
public static String Preference_Name = "AppData";
public static String getPreference(String key, String Default,
Activity activity)
{
sh_Pref = activity.getSharedPreferences(Preference_Name, Context.MODE_PRIVATE);
return sh_Pref.getString(key, Default);
}
public static void setPreference(String key, String value, Activity activity)
{
if (value != null)
{
sh_Pref = activity.getSharedPreferences(Preference_Name, Context.MODE_PRIVATE);
Editor editor = sh_Pref.edit();
editor.putString(key, value);
editor.commit();
}
}
}
** Here a set and get value from SharedPreferences**

sharedpreferences that don't change from activity to activity?

If i set a sharedpreference in one activity, why does the other one has different preferences? context changed? (but i se use application context!)
Here is my code
MyApp appState = ((MyApp)this.activity.getApplicationContext());
appState.setDittaSelezionata( (int) itemId);
....
MyApp appState = ((MyApp)this.getApplicationContext());
int ditta_id_selezionata = appState.getIdSomething();
And
public class MyApp extends Application implements Parcelable {
private SharedPreferences getSharedPrefs()
{
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
//SharedPreferences settings = this.getSharedPreferences(MyApp.PREFS_NAME, this.MODE_PRIVATE);
return settings;
}
public int getIdSomething() {
SharedPreferences settings = this.getSharedPrefs();
return settings.getInt("ditta_id_selezionata", 0);
}
public void setDittaSelezionata(final int ditta_selezionata) {
SharedPreferences settings = this.getSharedPrefs();
SharedPreferences.Editor editor = settings.edit();
editor.putInt("ditta_id_selezionata", ditta_selezionata);
// Commit the edits!
editor.commit();
}
...
How can i make global preferences that are shared among all activities android 3.2? is there something android provides or i have to code a save to file/open to file and add it for each activity onStop() / onCreate() ?
try this.
private static final String APP_PREF = "application_preference";
private static final String DITTA = "ditta_id_selezionata";
public class MyApp extends Application implements Parcelable {
private SharedPreferences getSharedPrefs(){
SharedPreferences settings = getApplicationConext().getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
return settings;
}
public int getIdSomething() {
SharedPreferences settings = this.getSharedPrefs();
return settings.getInt(DITTA, 0);
}
public void setDittaSelezionata(final int ditta_selezionata) {
SharedPreferences settings = this.getSharedPrefs();
SharedPreferences.Editor editor = settings.edit();
editor.putInt(DITTA, ditta_selezionata);
// Commit the edits!
editor.commit();
}
I think you had done something similar but commented it. This should keep your preferences constant throughout the app over the activities. As you see here, you make sure that the same preference file is being read and written to.
Shared Preferences ARE persisted across activities. If you're seeing different data then I expect the values are not being saved. I don't think the issue is the reading of the data, but the writing, so check your preference writing code.

Categories

Resources