Loading up value from SharedPreferences - android

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

Related

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 Shared Preferences?

I am new to android..and I'm developing an application using Json. I want to pass a string value from my main activity to another class without starting the activity class. I heard there is some way using shared preferences. I just tried.. but didn't worked..i got null point exception.. here is my code...
confirm = check.AuthenticateUser(name, passwd);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name",confirm);
editor.commit();
here is the place i want to send the value of "confirm" (string variable)
and below code shows where i want to get that preference..actually that class named "ShortList".
here is the code where i trying to get the value
public class ShortList extends Activity {
//ArrayList<HashMap<String, String>> arl;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String cargivr = preferences.getString("Name","");
please some one help me..
public static String CREDENTIALS_FILENAME = "com.myapp.credentials";
public static String PIN = "pin";
public static void writeCredentials(Context c,String pin) {
SharedPreferences credentialsPref = c.getSharedPreferences(CREDENTIALS_FILENAME, 0);
SharedPreferences.Editor editor = credentialsPref.edit();
editor.putString(PIN, pin);
editor.commit();
}
public static String readCredentials(Context c,String pin) {
SharedPreferences credentialsPref = c.getSharedPreferences(CREDENTIALS_FILENAME, 0);
SharedPreferences.Editor editor = credentialsPref.edit();
return credentialsPref.getString(PIN, "default value");
}
MainActivity.java
SharedPreferences pref = getApplicationContext().getSharedPreferences("New",Context.MODE_PRIVATE);
Editor edit = pref.edit();
edit.putString("SomeKey", "SomeValue");
edit.commit();
SecondActivity.java
SharedPreferences prefs = getApplicationContext().getSharedPreferences("New",Context.MODE_PRIVATE);
String value = prefs.getString("SomeKey","DefaultValue");
Also make sure that you have added the second activity details in your android manifest file -
<activity
android:name="com.example.projectName.SecondActivity"
android:parentActivityName="com.example.sharedpref.MainActivity">
</activity>
public class ShortList extends Activity {
//ArrayList<HashMap<String, String>> arl;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String cargivr = preferences.getString("Name","");
Here it seems you're initializing member variables.
You cannot use an Activity as a Context until onCreate() in the activity lifecycle. Member variable initialization is too early and will usually lead to NPE in getBaseContext().
Move the initialization of preferences and cargivr to onCreate() or later.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ShortList.this);
String cargivr = preferences.getString("Name","");

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.

Static SharedPreferences

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)

Categories

Resources