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.
Related
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.
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.
I know this has been asked before, but i can't seem to figure it out
i am trying to get my preferences by this:
SharedPreferences preferences = this.getActivity().getSharedPreferences("storedName", Context.MODE_PRIVATE);
String loginemail = preferences.getString("storedName", "");
but this doesn't seem to work, i have multiple sharedPreferences which i need to get in my fragment what is the correct way to do it?
As getDefaulSharedPreferences(this) doesn't work.
i store my prefs like so:
savePreferences("shareUniqePass", uniqePassIds.getText().toString());
savePreferences("storedName", inputEmail.getText().toString());
savePreferences("Storedpass", inputPassword.getText().toString());
private void savePreferences(String key, boolean value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor checkbox = sharedPreferences.edit();
checkbox.putBoolean(key, value);
checkbox.commit();
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor names = sharedPreferences.edit();
names.putString(key, value);
names.commit();
}
Instead of getting it from getSharedPreferences use the getDefaultSharedPreferences.
As getDefaulSharedPreferences(this) doesn't work.
You used getDefaultSharedPreferences for saving the data and therefore you must use getDefaultSharedPreferences to get the data that was saved.
this mean the instance of your fragment instead use the getActivity() to get the instance of context from your activity.
sample:
String loginemail = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(PREF_USER_NAME, "");;
You need to make sure that your saving and loading the data from the same shared preferences. If you're only accessing it from the one activity / fragment, you should use getDefaulSharedPreferences(this).
If, however, you're going to use it from several different activities / fragments, you should use:
private void savePreferences(String key, boolean value){
SharedPreferences prefs = getActivity().getSharedPreferences("storedName", Context.MODE_PRIVATE);
Editor checkbox = sharedPreferences.edit();
checkbox.putBoolean(key, value);
checkbox.commit();
}
In my Application class, I have the following:
public void loadPrefs(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Boolean soundValue = sharedPrefs.getBoolean("SOUND", false);
}
public void savePrefs(String key, boolean value){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sharedPrefs.edit();
edit.putBoolean(key, value);
edit.commit();
}
All OK there as far as I can tell.
Now in my main class which extends SurfaceView, I have the following:
myApp mySettings = (myApp)getContext().getApplicationContext();
Then I can save values like so: (Again from my surfaceView activity)
myPlanSettings.savePrefs("SOUND", false);}
However, what I just cannot work out is how to read the value back so I can set a local variable like so:
Boolean thisValue = (the value from the shared preferences).
Thanks for any help
Try this
public Object loadPrefs(String key,String defaul){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
return sharedPrefs.get(key,default);
}
Cast it with the type while using getting the value
Basic usage:
boolean b=(Boolean)loadPrefs("value","default value")
I have two methods in an activity
private void save(String tag, final boolean isChecked)
{
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(tag, isChecked);
editor.commit();
}
private boolean load(String tag) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(tag, false);
}
and I wan't to make the load static for the purposes of retrieving the values of load from another static method within the same activity. However, when I try to make the load method static, I of course get an error because of a non-static reference. How can I make this work?
I tried this Accessing SharedPreferences through static methods with no luck.
Any help would be much appreciated!
You could save and load from Application-wide shared preferences instead of prefs private to the Activity:
private static boolean load(String tag) {
SharedPreferences sharedPreferences = Context.getApplicationContext().getSharedPreferences("namespace", Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(tag, false);
}
If you do this, make sure you are also storing the preferences in the same way (by using Context.getApplicationContext().getSharedPreferences)