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.
Related
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.
Hello guys I've ColorPicker in my app. When I set the color selected by ColorPicker to the Activity background, it works. But when I restart the app, the color changes to default! How to save the state of Activity? Is it possible? Thanks in advance!!!
So for example you can save the color like this (I've just put a hex color reference but you can change it to whatever you wish):
public void setBackgroundColor() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("color", "#FFFFFF");
editor.commit();
}
Then just make sure you call this method every time it loads / reloads:
public void getBackgroundColor() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
if (sharedPreferences.contains("color")) {
String myColor = sharedPreferences.getString("color", null);
mybackground.setBackgroundColor(Color.parseColor(myColor));
}
}
Andy's Answer is correct. However, I thought I would chime in on saving and loading preferences. These are universal Save/Load methods for Strings. It's what I use in all my activities. It can save you a lot of headaches in the future!
public static String PREFS_NAME = "random_pref";
static public boolean setPreference(Context c, String value, String key) {
SharedPreferences settings = c.getSharedPreferences(PREF_NAME, 0);
settings = c.getSharedPreferences(PREF_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
static public String getPreference(Context c, String key) {
SharedPreferences settings = c.getSharedPreferences(PREF_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME , 0);
String value = settings.getString(key, "");
return value;
}
I am trying to figure out how I would achieve storing image URLs via onClick of an item button so they can be accessed by another class.
I have looked around and saw that it would be best to achieve this using shared preferences.
I have never used shared preferences before so I am a little confused as how I will be able to achieve this because I would like to get the URL from the String I have called "mImageUrl"
I know my String "mImageUrl" will give me the URL of the image that is currently being viewed, so I like to somehow store the String/URL from my String to shared preferences so the specific URLs can used via another class.
Would using shared prefs be a good way to achieve my requirement,
Any guidance would be appreciated thanks
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.SetWallpaper:
new SetWallpaperAsync(getActivity()).execute(mImageUrl);
break;
case R.id.SaveWallpaper:
new SaveWallpaperAsync(getActivity()).execute(mImageUrl);
break;
case R.id.FavouriteWallpaper:
//Use shared preferences here somehow:
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
SharedPreferenceUtil.setSharedPreference(context, "ImageKey", mImageUrl);
String url = SharedPreferenceUtil.getSharedPreference(context,"ImageKey",null);
if(url != null){
// set image source here..
}
break;
}
return super.onOptionsItemSelected(item);
}
Try this code:
Save in SharedPreferences :
SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(contextActivity);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("imgUrl", UrlString);
editor.commit();
To retrive value:
prefs = PreferenceManager.getDefaultSharedPreferences(contextActivity);
prefs.getString("imgUrl", null);
try this
in one Activity :
SharedPreferences sp;
SharedPreferences.Editor edit;
sp = getSharedPreferences("enter", MODE_PRIVATE);
edit = sp.edit();
edit.putString("imagerul", user_validate);
edit.commit();
in next activity :
SharedPreferences sp = getSharedPreferences("enter", MODE_PRIVATE);
sp.getString("imageurl", "fdgf"));
You can simple implement a class that handles get/set operations of shared preferences.
I will provide a class so that you can easily integrate to your project.
Here is our SharedPreferenceUtil class
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreferenceUtil {
public static String getSharedPreference(Activity activity, String prefName, String key, String defaultValue){
SharedPreferences prefs = activity.getSharedPreferences(prefName,0);
String pref = prefs.getString(key, defaultValue);
return pref;
}
public static void setSharedPreference(Activity activity, String prefName, String key, String value){
SharedPreferences prefs = activity.getSharedPreferences(prefName,0);
SharedPreferences.Editor editor = prefs.edit();
// edit and commit
editor.putString(key, value);
editor.commit();
}
}
You can simply set/get preference from your activity with the following code sample.
// You can set your shared preferences like following.
SharedPreferenceUtil.setSharedPreference(this.getActivity(),"pref","yourImageKey","yourImageUrl");
// and you can get your shared preferences like following.
String url = SharedPreferenceUtil.getSharedPreference(this.getActivity(),"pref","yourImageKey",null);
if(url != null){
}
EDIT:
You can reach SharedPreferences from a Fragment by following
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
Hope this may help.
Try:
SharedPreferences pr=PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor r=pr.edit();
r.putString("name","yourlink");
r.commit();
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.
I am developing an android application in which i have to do the following thing
At the start of the app, first thing it should do is ask user to enter name and then through a welcome screen with that name.
Then When the app is used next time it should just give welcome screen (should not ask for name again)
I have created the code for the above.
I have used shared preference saved
My code is
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}
But how to check whetehr user is already registered?
Thanks
Tushar
But how to check whetehr user is already registered?
When user starts application first time that time you will check if any preference value exists for name key.
Following snippet will help you
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String namePrefrence = sharedPreferences.getString("uname", "");
if (namePrefrence.length() == 0) {
//User not registered!!
Show dialog where user will enter username
} else {
//User is registered!!
just show welcome screen
}
Well to use SharedPrefernces.. use this::
first declare it...
public static final String PREFS_NAME = "PrefernceNAme";
public static final String PREFS_ITEM = "PrefItemStored";
to get values from it, use:::
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
mode = preferences.getString(PREFS_ITEM, "PrefItemStored");
and to add values in SharedPrefernces, use::
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_ITEM, value)
.commit();