This question already has answers here:
TextView that gets Value from SharedPreferences shows nothing, though there should be default values
(4 answers)
Closed 6 years ago.
I am having an issue with SharedPreferences that is kind of weird.
I have an Activity that holds a Fragment in a ViewPager. The fragment shows an icon and text. You can change the icon (check mark or cross, check mark is default) and text displayed in this fragment from another activity.
Now I want to save the text and chosen icon, so the fragment is shown with the same text and icon, even when you close the app and restart it later.
So I tried to achieve this with SharedPreferences, but when I tried it, my fragment showed me no text though I have default values set and the icon is always the cross, no matter what it was before and though the default icon should be the check mark.
I am saving the values in onActivityCreated() of my Fragment when it is created with the data the user inputted in the activity before.
Saving:
SharedPreferences sharedPref = getActivity().getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//Here I am getting the values I want to save from a bundle, city and country...
editor.putString("savedCity", city);
editor.putString("savedCountry", country);
editor.putString("fragmentSaved", "yes");
editor.apply();
Then, I am getting the values in onCreate() of my Activity that holds the Fragment:
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//adding fragment that was created with user input
String ifAdded = sharedPref.getString("addedFragment", "no");
if(ifAdded.equalsIgnoreCase("yes")){
Bundle extras = getIntent().getExtras();
StatusFragment newFragment = new StatusFragment();
newFragment.setArguments(extras);
mSectionsPagerAdapter.addFragment(newFragment, extras.getString("city"));
editor.putString("addedFragment", "no");
editor.apply();
}
//Adding a saved fragment after restart
String storedSave = sharedPref.getString("fragmentSaved", "no");
if (storedSave.equalsIgnoreCase("yes")){
String storedCity = sharedPref.getString("savedCity", "somecity");
String storedCountry = sharedPref.getString("savedCountry", "somecountry");
Bundle saves = new Bundle();
StatusFragment savedFragment = new StatusFragment();
saves.putString("city", storedCity);
saves.putString("country", storedCity);
savedFragment.setArguments(saves);
mSectionsPagerAdapter.addFragment(savedFragment, saves.getString("city"));
}
In the activity where the fragments data is created, I have this:
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("addedFragment", "yes");
editor.apply();
fragmentHolder.putExtras(bundle);
startActivity(fragmentHolder);
bundle has the values the user typed in, and fragmentHolder is the activity that holds the fragment.
I searched for answers in different questions here on stackoverflow, but none of them worked for me, like:
Cannot get value from sharedpreferences
Shared Preferences get lost after shutting down device or killing the app
Shared Preferences reset data when app is force closed or device is restarted
SharedPreferences return only default value
SharedPreferences return only default value
Shared preference always taking default value
SharedPreferences keep getting default value
Sorry if I it is perhaps something trivial, but I haven't worked with Fragments much and I am using SharedPreferences the first time now.
I would be grateful for every helpful answer.
The problem is solved now. I had to use getActivity().getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE); and some of my variables in the bundles and preferences got mixed up. I corrected this and now it works fine :) Thanks for your answers.
You are mixing up things that are stored in your SharedPreference and inside your applications resources (strings.xml)
editor.putString(getString(R.string.pref_fragment_saved), "Yes");
This line saves the string inside your preference XML, but then you try to read it as
getResources().getString(R.string.pref_fragment_saved).equals("Yes")
Which actually just reads the value R.string.pref_fragment_save from your strings.xml
The correct way of reading what you saved would be
getActivity().getPreferences(Context.MODE_PRIVATE).getString(getResources().getString(R.string.pref_fragment_saved), "defaultValue")
Or a bit cleaner:
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
String key_frag_saved = getResources().getString(R.string.pref_fragment_saved);
String storedString = prefs.getString(key_frag_saved, "defValue");
if ( storedString.equalsIgnoreCase("yes") ) {...}
And the same way you would read the other saved values from your SharedPreference object instance.
You wanted to use this
SharedPreferences sharedPref = ...;
extras.putString("city", sharedPref.getString(getResources().getString(R.string.pref_saved_city), ""));
in your onCreate method
Related
in my application, I used place picker.and data that place picker gave is sent to 3 different activities using shared preference.and show this data in TextView.problem is when I closed activity and again open that activity my data still visible in TextView.even when I cleared it in onDestroy().
here is my code for send data from place picker:
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("city_address", (String) cityAddress);
editor.putString("city_name", (String) city);
editor.commit();
Intent intent = new Intent(this, CleanlinessActivity.class);
startActivity(intent);
set data using this code in onCreate() of CleanlinessActivity
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
String n = settings.getString("city_name", "Enter Location");
String a = settings.getString("city_address", "");
cityname.setText(n);
cetlocation.setText(a);
and i cleared data using this code in CleanlinessActivity
#Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("city_address");
editor.clear().commit();
}
By closing the app you mean just clicking the home button then onDestroy() is never called, you can get a refresher of the android life cycles here
If what you are doing is simply clicking the home button then consider moving your code to the onStop() otherwise you need to commit() following the remove(...) The android documentation states "Mark in the editor that a preference value should be removed, which will be done in the actual preferences once commit() is called."
You have an instance of SharedPreferences called city_address which is having two fields or (Columns if we call it),but inside onDestroy()you are trying to to clear only one field of it called city_address,and the other field city_name field is left unchanged,if you want to completely remove the content of the city_address SharedPreferences use editor.clear().commit();
or``editor.clear().apply();`
I have 2 int in my navigation drawer, the value of whom changes upon clicking different button on different locations in the app.
I got the code to successfully increment and update them, but the problem is that they got reset when I open the app after closing or exiting it.
How can I make them stay there after getting updated?
If you want any code from my app, then please tell me.
Sorry for bad formatting of the question, but I have no idea how to do this and hence I haven't posted any code.
You must save the info in a persistent storage.
You can use SharedPreferences.
SharedPreferences prefs= getSharedPreferences("aName", MODE_PRIVATE);
//save the value
prefs.edit()
.putInt("nameOfTheValue", theValue).apply();
// get the data
prefs.getInt("nameOfTheValue", aDefaultValue);
You should save them as User SharedPreferences in onDestroy method.
public void onDestroy() {
super.onDestroy();
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//set the sharedpref
Editor editor = settings.edit();
editor.putInt("FIRST_INT", firstIntValue);
editor.putInt("SECOND_INT", secondIntValue);
editor.commit();
}
And then you can get them back wen needed:
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//get the sharepref
int firstInt = settings.getInt("FIRST_INT", 0);
int secondInt = settings.getInt("SECOND_INT", 0);
my activity has a string which gets its value from an intent
String myString = intent.getStringExtra("KEY");
in this activity I start another activity. From the new activity I want to return to the previous activity and still have the same value of myString. But when I open a the new activity the value of myString is deleted.
i looked into onSavedInstancState but that doesn't seem to work.
making myString static works but I think that this is not good programming.
So what would be the best way of doing this?
Use ShareDPreferences to store an object that you want to retrieve later:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("key", ""KEY");
editor.commit();
To retrieve it later:
pref.getString("key", null);
You can use SharedPreferences,
If you have a relatively small collection of key-values that you'd
like to save, you should use the SharedPreferences APIs.
I've got a really weird problem with my shared preferences. I'm using them to store the user-ID, different settings and so on. I'm using an activity which switches fragments if a user has clicked an item in my menu (I'm using Menu-Drawer).
After every login I store the user profile. This works perfect. After doing this I can restart the app, kill it from the memory, I can even restart my device and my values are still stored. But when I switch the fragment, e.g I'm in the home view and click "about app" in the menu, everything is gone. My values are empty.
Where it gets even weirder: If I force the activity to reload the fragment by selecting the home-item while I'm already in the home view, it's still stored. Only if I replace it with a different type of fragment everything is lost.
I don't have any idea why the app behaves like this. It's all in the same activity with the same context. I'm always using getActivity to get my context inside the fragment.
Here's a simplified snippet of my code to store it.
public static void storeUserProfile(Context context, LoginEvent event, String userId, String emailAddress, String passwordHash) {
SharedPreferences userPrefs = context.getSharedPreferences(AppConfig.USER_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userPrefs.edit();
editor.clear();
editor.putString("username", event.userName);
editor.putString("id", userId);
editor.putString("email", emailAddress);
editor.commit();
}
This is how I switch my fragments:
HomeFeedFragment fragment = new HomeFeedFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
Try this snippet, it can be accessed from all activities/ fragments in your app.
Declare these methods first..
public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
Then call this when you want to put a pref:
putPref("myKey", "mystring", getApplicationContext());
call this when you want to get a pref:
getPref("myKey", getApplicationContext());
Using fragments, does not work with getSharedPreferences() only with
PreferenceManager.getDefaultSharedPreferences (getActivity ());
Thank you very much for the fast responses! I've found the error myself. For the about view, I'm loading an html file which will be stored in shared preferences too. I haven't thought about the fact that sharedpreferences are just an xml file so I think that the html string made the xml file invalid.
I've noticed that my prefs.getString(key, defaultValue) weren't returning the defaultValue, they were returning an empty String. So I've removed the html storing and do this in a different way.
But thank you for your comments!
I had the same problem, i solved by changing the key string of my sharedpreferences
I was using :
SharedPreferences userPrefs = context.getSharedPreferences("MuslimActive", Context.MODE_PRIVATE);
I changed with :
SharedPreferences userPrefs = context.getSharedPreferences("muslim_active", Context.MODE_PRIVATE);
Anything past 2.3 and MODE_MULTI_PROCESS is disable by default, and if multiple instances of the same SharedPreferences exist MODE_MULTI_PROCESS will need to be set.
Try:
getSharedPreferences(AppConfig.USER_PREFS, Context.MODE_MULTI_PROCESS);
Also, make sure you are consistently using AppConfig.USER_PREFS in your method calls.
In my application I want to clear SharedPreferences on button click. This is what I'm using for storing values in it:
SharedPreferences clearNotificationSP = getSharedPreferences("notification_prefs", 0);
SharedPreferences.Editor Notificationeditor = clearNotificationSP.edit();
Notificationeditor.putString("notificationCount", notificationCountValue);
Notificationeditor.commit();
And the following code on onClick():
SharedPreferences clearedNotificationSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editorSP = clearedNotificationSP.edit();
editorSP.remove("notificationCount");
editorSP.commit();
System.out.println("Saved in SP clearedNotification: "+ clearNotification);
I was printing the value after clearing it but still I was getting the same value.
What am I missing?
Any kind of help will be appreciated.
getDefaultSharedPreferences and getSharedPreferences("notification_prefs", );
returns two different SharedPreferences. Since you are adding notificationCount inside notification_prefs, you should retrieve SharedPreference with getSharedPreferences("notification_prefs", );
getDefaultSharedPreferences uses a default preference-file name, while getSharedPreferences use the filename you provided as paramter