Using shared preferences in between activities - android

I am trying to share a shared preference in between two activities of my project, but for some reason I am not able to pass the data.
I have Activity A which reads the shared preference and Activity B that reads as well as edit that shared preference.
Here is the code I am using to write the shared preference in Activity B:
SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.
MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("theme", "black");
editor.commit();
and for reading in Activity A:
SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.
MODE_WORLD_WRITEABLE);
String theme=sharedPref.getString("theme","blue");
I have tried using the different modes, and it worked in Activity B in PRIVATE mode but it wasn't shared to activity A. For some reasons I think I have two different shared preferences(same name) for the two different activities. How do I use the same shared preference for both the activities ?

You can do simpler - in any activity:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
You will have the same prefs this way from anywhere.
http://developer.android.com/reference/android/preference/PreferenceManager.html#getDefaultSharedPreferences(android.content.Context)

To read shared datas in the second activity , change the mode :
from MODE_WORLD_WRITEABLE to MODE_WORLD_READABLE
SharedPreferences sharedPref = getSharedPreferences("myPrefs",Context.MODE_WORLD_READABLE);
String theme=sharedPref.getString("theme","blue");

// try this way
1. define SharedPreferences variable in SmartApplication class also define read and write method SharedPreferences
private SharedPreferences sharedPreferences;
#Override
public void onCreate() {
super.onCreate();
sharedPreferences = getSharedPreferences("yourAppName", MODE_PRIVATE);
}
public void writeSharedPreferences(String key, String value) {
SharedPreferences.Editor editor = readSharedPreferences().edit();
editor.putString(key, value);
editor.commit();
}
// write Shared Preferences
public void writeSharedPreferences(String key, boolean value) {
SharedPreferences.Editor editor = readSharedPreferences().edit();
editor.putBoolean(key, value);
editor.commit();
}
// write Shared Preferences
public void writeSharedPreferences(String key, float value) {
SharedPreferences.Editor editor = readSharedPreferences().edit();
editor.putFloat(key, value);
editor.commit();
}
public void writeSharedPreferences(String key, int value) {
SharedPreferences.Editor editor = readSharedPreferences().edit();
editor.putInt(key, value);
editor.commit();
}
// write Shared Preferences
public void writeSharedPreferences(String key, long value) {
SharedPreferences.Editor editor = readSharedPreferences().edit();
editor.putLong(key, value);
editor.commit();
}
// get Shared Preferences
public SharedPreferences readSharedPreferences() {
return sharedPreferences;
}

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

SharedPreferences doesn't work android

I have a sharedPreferences object and SharedPreferencesEdit object but doesn't save anything
public void getPreferences(){
SharedPreferences sp = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = sp.edit();
spEditor.putString("us1_Name", us1_Name.getText().toString());
spEditor.commit();
}
public void setPreferences(){
SharedPreferences sp = getSharedPreferences("MyData", Context.MODE_PRIVATE);
us1_Name.setText(sp.getString("us1_Name", "DEFAULT"));
}
I call this methods when onStop and onResume call, but doesn't work for me.
You just need to exchange your preference methods from your getPreferences() to setPreferences() like
public void getPreferences(){
SharedPreferences sp = getSharedPreferences("MyData", Context.MODE_PRIVATE);
us1_Name.setText(sp.getString("us1_Name", "DEFAULT"));
}
public void setPreferences(){
SharedPreferences sp = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = sp.edit();
spEditor.putString("us1_Name", us1_Name.getText().toString());
spEditor.commit();
}
in your getPreferences() you need to get saved preferences value by using
sp.getString("us1_Name", "DEFAULT")
in your setPreferences() you need to saved preferences value by using
SharedPreferences.Editor spEditor = sp.edit();
spEditor.putString("us1_Name", us1_Name.getText().toString());
spEditor.commit();
first thing is that
1.) don't do any operations like sharedPreferance Edit / Database edit in onStop(); method
because it just call just for moment and it is only for do minor operation regarding activity
so please change it and do it in onPause();

Cannot get SharedPreferences value from one activity to another in Android

I am using shared preferences for saving data and accessing it from another activity. I have used suggested methods but they don't seem to work.
Code:
private static String Module_Pref="ModulePreference";
Activity A:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
Activity B:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
tempValue= sharedPreferences.getString(Module_Pref, "empty");
Activity C:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
Here if we run first time then pass through A, set nosave, then if we go to activity C then save the data.
What is wrong with this code.I am getting a null. I looked at file explorer also where pref file isn't saved.
use this method to create a sharedPreference and then access it with this same name from any where in any activity within the same app
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
Editor e = sp.edit();
e.put(key,value);
e.commit();
and when getting the same sharedPreference in another activity use this method
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
sp.get(key,value);
`
Your should use for entering data like this:
editor.putString(Module_Pref, "value that you want to store");
editor.commit();
Now For getting that String you can use this after storing the value:
sharedPreferences.getString(Module_Pref, "empty");
sharedPreferences.getString(Module_Pref, "empty");
means you want to retrieve the "value" for the key- Module_Pref, if there is none, by default it will return -> "empty" .
So either,
editor.putString(Module_Pref, value);
Or
sharedPreferences.getString(key, "empty");
where "key" is same as the key in:
editor.putString(key, value);
Activity A:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key,value );
editor.commit();
Activity B:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
tempValue= sharedPreferences.getString(key, "emptyValue");
SharedPreferences sp = getSharedPreferences("main",0);
SharedPreferences.Editor ed = sp.edit();
ed.putString("personEmail",personEmail);
ed.putString("personName",personName);
ed.commit();
this is used for saving values in shared pref & for accessing it use ->
SharedPreferences sp = getSharedPreferences("main",0);
sp.getString("personEmail",null);
sp.getString("personName",null);

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.

Categories

Resources