Static SharedPreferences - android

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)

Related

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.

sharedPreferences in Fragment

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();
}

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.

Loading up value from SharedPreferences

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")

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