sharedpreferences that don't change from activity to activity? - android

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.

Related

SharedPreferences saves state between android activities but not upon restarting the app

I'm running to a really weird behavior with SharedPreferences. I'm wondering if I'm running into a synchronization issue.
It seems like the app can remember the preference changes in between activities but not when I restart the app. The state always returns back to the very first instance I created a preference. I've followed several examples, tutorials, and android documentation that all suggest similar code layout. I also watched how the preference.xml file changed while interacting with my code using the debugger and I confirmed it looked like the key value pair updated.
Could I be experiencing a synchronization issue with my emulator? I tried using both the editor.apply() method and editor.commit() method with the same results.
The only thing I've found that fixes my problem is using the editor.clear() method, but this feels a bit hacky...
note: please forgive the variable names, I'm making a pokedex...
public class SecondActivity extends AppCompatActivity {
private boolean caught;
private Set<String> pokemonCaught;
private String pokemonName;
public SharedPreferences sharedPreferences;
public static final String SHARED_PREFERENCES = "shared_preferences";
public static final String PREF_KEY = "inCaughtState";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*SKIPPING THE VIEW SETUP*/
/*SKIPPING BUTTON VIEW ATTRIBUTES*/
//variables required for changing button state
pokemonName = (String) nameTextView.getText();
caught = false;
//Loading in sharedPreferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
pokemonCaught = sharedPreferences.getStringSet(PREF_KEY, new HashSet<String>());
if (pokemonCaught.contains(pokemonName)) {
toggleCatch(catchButton);
}
}
public void toggleCatch (View view) {
//Editing and updating preferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (caught == true) {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = false;
pokemonCaught.remove(pokemonName);
}
else {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = true;
pokemonCaught.add(pokemonName);
}
editor.clear(); //This is my hacky solution...
editor.putStringSet(PREF_KEY, pokemonCaught);
editor.apply();
}
}
Try to use SharedPreferences this way:
To save data
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("stringName", "stringValue");
editor.apply();
To retrieve data
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PREFS", MODE_PRIVATE);
String name = preferences.getString("stringName", "none"));
Note that this "none" is in case to string "stringName" be null.

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.

SharedPreference not available after app restart

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

Android - SharedPreference error

Problem: Activity B ALWAYS return false, however, if I check the same KEY inside activity A, the result is true. Why is this? I have checked the KEY, it is exactly the same in both activities.
Edit: Thank you all for your help, however after implementing your suggestions, I still have had no luck. Here is what I have now:
ActivityA, extends Activity Implements OnGesturePerformedListener
//How methods are called...
read(getApplicationContext(),"fav", posName);
write(getApplicationContext(), "fav", posName, false);
...
public Boolean read(Context context, String name, String key) {
SharedPreferences sP = context.getSharedPreferences(name, MODE_PRIVATE);
Boolean b = sP.getBoolean(key, false);
return b;
}
public void write(Context context, String name, String key, boolean value) {
SharedPreferences sP = context.getSharedPreferences(name, MODE_PRIVATE);
SharedPreferences.Editor editor = sP.edit();
editor.putBoolean(key, value);
editor.commit();
}
ActivityB, extends FragmentActivity, sub class:
public static class SectionFragment extends Fragment
Inside onActivityCreated()
SharedPreferences sP = getActivity().getSharedPreferences("fav", MODE_PRIVATE);
Boolean b = sP.getBoolean(posName, false);
Results = b always equals false
Any Ideas?
Use getSharedPreferences`:
public void write(Context context, String key, boolean value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
NAME_SHAREDPREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public Boolean read(Context context, String key) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
NAME_SHAREDPREFERENCES, MODE_PRIVATE);
Boolean b = sharedPreferences.getBoolean(key, false);
return b;
}
From the Android docs:
Activity persistent state is managed with the method getPreferences(int), allowing you to retrieve and modify a set of name/value pairs associated with the activity. To use preferences that are shared across multiple application components (activities, receivers, services, providers), you can use the underlying Context.getSharedPreferences() method to retrieve a preferences object stored under a specific name.
(http://developer.android.com/reference/android/app/Activity.html)
So basically you need to use Context.getSharedPreferences() to share preferences across multiple activities.
You can adopt the following approach to get same sharedPreference everywhere:
SharedPreference mPrefs = PreferenceManager.getDefaultSharedPreference(getApplicationContext());
SharedPreference.Editor mEditor = mPrefs.edit();
I hope it was useful.

How to use shared preference data in different classes in android?

Using shared preferences I saved data in one of the activity Now I want to use that data in another activity how to do that?
Create a sharedPreference where you want to add shared data. A little example of code like this:
SharedPreferences prefs = this.getSharedPreferences("CONSTANT_FILE_NAME",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("isPaid", true);
editor.commit();
And to retrieve that shared data use this code:
SharedPreferences prefs = this.getSharedPreferences("CONSTANT_FILE_NAME",
Context.MODE_PRIVATE);
prefs.getBoolean("isPaid",false);
Read this from developer site: click here
PREFS_NAME is the value you stored in shared preference.
public static final String PREFS_NAME = "MyPrefsFile";
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false)
Look at Restoring preferences
Edited:To use it among all classes i.e. setter getter method.Perfect use of OOPS.You can call the value from any class thats 1-line job
Make a normal class name as ReturningClass.
public class ReturningClass {
private static String MY_STRING_PREF = "mystringpref";
private static String MY_INT_PREF = "shareduserid";
public static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences("UserNameAcrossApplication", context.MODE_PRIVATE);
}
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, 0);
}
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();
}
Set your value by calling
ReturningClass.setMyIntPref(mContext,22);
Once You have set your sharedPreference.Then just call this method.Just pass the context.from your class
int usersharedpreference=ReturningClass.getMyIntPref(mContext);
This link can help you.
Unable to use shared preference values in class A extends BroadcastReceiver , Android
also
http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html
//decleration
SharedPreferences saveWord;
//onCreate
saveWord=PreferenceManager.getDefaultSharedPreferences(ActivityName.this);
String word=saveWord.getBoolean(PREFS_NAME, false);

Categories

Resources