Accessing SharedPreference not working in Android - java

I have two activities. In the first activity, I'm putting a String into a shared preference. I then log the getString and I see that it shows up. I then move onto the second activity, and I Toast the getString and I get the default value that shows up.
The first activity code:
SharedPreferences.Editor pref_editor = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE).edit();
SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
pref_editor.putString("test", "It works!").commit();
Log.d("XXX", pref.getString("test", "ERRRROR"));
The second activity code:
SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
String current = pref.getString("test", "ERROR");
Toast.makeText(getApplicationContext(), current,
Toast.LENGTH_SHORT).show();
Any idea why I'm getting the default value of "ERROR" when I toast?

Please try this:-
SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor pref_editor = pref.edit();
pref_editor.putString("test", "It works!")
pref_editor.commit();

You aren't calling commit on the editor. The changes are batched and not written to disk until commit is called.

From this SO post Have you tried apply()?

Related

sharedPreferences is not working to between two fragment?

fragment 1:
SharedPreferences sPrefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString("name", "testnameJack");
editor.commit();
fragment 2:
SharedPreferences sPrefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String data= sPrefs.getString("name", "err");
emailId.setText(data);
I want transfer data to between two fragment but not working
Try:
SharedPreferences sPrefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String data= sPrefs.getString("name","No name defined");
emailId.setText(data);
This isn't how it works. If you update SharedPreferences while both fragments are on screen... how would they know that the preference had changed. There are two ways to solve this easily:
1) Add an OnSharedPreferenceChangeListener to the preferences in the fragment you are attempting to update. When the listener detects a change you can alter your text. In your case fragment 2. for example:
sPrefs.registerOnSharedPreferenceChangeListener(
new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// .. Check the key to see if its the one you are looking for then set the text
}
});
Don't forget to unregister the listener to avoid leaks though.
2) Implement an interface in the parent Activity or Fragment and call a public method from the Activity in Fragment 2.
see docs
Good Luck and Happy Coding!
answer:
//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;
prefsEditor = myPrefs.edit();
//strVersionName->Any value to be stored
prefsEditor.putString("STOREDVALUE", strVersionName);
prefsEditor.commit();
//Get Preferenece
SharedPreferences myPrefs;
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String StoredValue=myPrefs.getString("STOREDVALUE", "");
Thanks everyone :)

I need to set the value of a global variable and save it even on restarting the app

So I'm developing a feature in an app where I have a boolean set to true which leads to some action being done. Now, onClick of a button will do a few related tasks and also set the boolean to false. That's fine and it works great, but once it has been changed to false, I want that on restarting the app it is assigned as false instead of true. I've tried searching for a while without any luck. Help will be appreciated.
I've only been learning Java and Android app dev for 2 months and now I'm making programs, so kindly bear with me. Maybe some sort of use of Boolean instead of boolean? I haven't got too far though.
public class Constants {
public static boolean VARIABLE = true;
}
public Fragment {
mSharedPreferencesManager.setFeatureUpdateCheck(Constants.VARIABLE);
if(mSharedPreferencesManager.getFeatureUpdateCheck())
chatUpdateNotif.setVisibility(View.VISIBLE);
else
chatUpdateNotif.setVisibility(View.GONE);
#OnClick (R.id.chat_notification_close_button)
public void onClickHideNotification() {
chatUpdateNotif.setVisibility(View.GONE);
Constants.VARIABLE = false;
Your question is very unclear.If you are trying to save a value in closing the application and getting the value back on restart try using shared preferences.
1.Save the value on click of button
SharedPreferences sharedPref = getSharedPreferences("YOUR PREF NAME", Context.MODE_PRIVATE);
sharedPref.edit().putBoolean("VALUE NAME", true).apply();
2.Restore the value from preferences on restring app
sharedPref.getBoolean("VALUE NAME", null);
Edit:If your are not using activity use context to use preference
SharedPreferences sharedPref = context.getSharedPreferences("YOUR PREF NAME", Context.MODE_PRIVATE);
Use Shared Preferences to save the boolean value when it is changed like this:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"DataSaved", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("VARIABLE", VARIABLE);
editor.commit();
Then in Constant write this:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"DataSaved", Context.MODE_PRIVATE);
VARIABLE = sharedPref.getBoolean("VARIABLE", false);
private String MY_PREFS_NAME = "sharedPref";
This sets the boolean:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("Value", false);
editor.commit();
This gets the boolean:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
TextView textview = (TextView)findViewById(R.id.textview);
textview.setText(String.valueOf(prefs.getBoolean("Value", true)));
This textview will print out false, because the boolean has been set. If the boolean was not set it would be true (default value).

Saving changed Activity background colour on button click

I have this code which allows me to change the background colour of my activity and I call this on a button click.
View someView = findViewById(R.id.mainLayout);
View root = someView.getRootView();
root.setBackgroundColor(0xFF00FF00);
How can I save the background colour so that it stays changed whenever the app is restarted.
If you need to persist this setting across multiple starts by the user use SharedPreferences as described here:
http://developer.android.com/training/basics/data-storage/shared-preferences.html
If you only want to keep this setting when re-created by the system because of orientation changes for example, use onSaveInstanceState() and check for a Bundle in onCreate() as described here:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
Save to SharedPref.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(KEY, Value);
editor.commit();
Read from SharedPref.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int i = sharedPref.getInt(KEY, defaultValue);
Set Flag in sharedPreferences by
Editor editor = sharedpreferences.edit();
editor.putString(Flag, "Y");
And while loading the screen in Oncreate check for the flag by
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Flag))
{
name.setText(sharedpreferences.getString(Flag, ""));
}

Android: SharedPreferences not getting pulled in another activity

I am currently having some trouble getting a shared preference in another activity. I currently have the following set up in my main activity:
OnCreate method:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String tut = preferences.getString("KEY", "");
ip = tut;
Then I have a menu to edit the preference:
SharedPreferences.Editor editor = getPreferences(
MODE_PRIVATE).edit();
String value = input.getText().toString();
editor.putString("KEY", value);
editor.commit();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String tut = preferences.getString("KEY", "");
ip = tut;
However when I try to receive the data in another activity in its OnCreate method it doesn't get the data:
Second Activity:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String tut = preferences.getString("KEY", "");
ip = tut;
Any ideas?
instead of using "getPreferences(0)" you need to set and use shared preferences with his own name, this is an example:
//Fragment Activity One
SharedPreferences prefs = getActivity().getSharedPreferences("user",0);
SharedPreferences.Editor setPrefs = prefs.edit();
setPrefs.putString("name",profile.getName());
setPrefs.putString("email",profile.getEmail());
setPrefs.putString("idFacebook",profile.getIdFacebook());
setPrefs.putString("password",profile.getPassword());
setPrefs.putString("bio",profile.getBio());
setPrefs.putInt("id",profile.getId());
setPrefs.commit();
//Fragment Activity Two
SharedPreferences prefs = getActivity().getSharedPreferences("user",0);
String name = prefs.getString("name","")
thats how i use SharedPreferences, hope it help
You are using the private version of shared preferences; how you are using it, the values can only be seen by the originating Activity. You should be using getSharedPreferences(String, int); instead. Learn more at: http://developer.android.com/guide/topics/data/data-storage.html#pref

Custom DialogPreference in Android

In My Project I am using SeekBarPreference. I take reference from http://android.hlidskialf.com/blog/code/android-seekbar-preference code work perfect without any error but when i fetch share Preference value in other activity. then i always found 0 why?
I use below code for get share Preference value:-
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String str=Integer.toString( prefs.getInt("duration", 0));
Using Shared preferences code for get and put the values below:
code for put the values into sharedpreferences:
public static final String PREFS_NAME = "Prefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("no", 11);
editor.commit();
Code for get the values from sharedpreferences:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
String in=Integer.toString(settings.getInt("no", 0));

Categories

Resources