I wanna add an integer dynamically in the getCount() method of custom pager adapter that obviously extends FragmentStatePagerAdapter.
return some integer value;
I have a counter saved in Shared Preference object and it gets updated with clicks on star images. I wanna return the updated counter value in the mentioned method, so I can generate that many swipe views but the problem is I unable to get Shared Preference object there. This is the only obstacle between my app and the play store, I've been developing it for like month or two. So please gimme suggestion on this issue I'm facing. Thanks in advance guys!
https://developer.android.com/training/basics/data-storage/shared-preferences.html
https://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String, int)
Set your value onPause() and onStop and read your value onResume and onCreate.
You need to set a final string which would be your SharedPreferences filename.
Get your value and increment
Writing:
SharedPreferences sharedPref = getSharedPreferences(YOUR_FINAL_STRING, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_value), newValue);
editor.commit();
Reading:
SharedPreferences sharedPref = getActivity().getSharedPreferences(YOUR_FINAL_STRING, Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_value_default);
long value = sharedPref.getInt(getString(R.string.saved_value), defaultValue);
First read the value and set it to a variable in shared preferences.
Increment the same value onPause or onStop.
Related
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
How to display an AlertDialog based on the number of execution of an activity(MainActivity). For example if MainActivity is opened for 5 times then i need to display an AlertDialog.
Saving data in Preference:
private static void saveCounter(Context context, int value) {
SharedPreferences prefs = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("count", value);
editor.commit();
}
Retrieve data from preference:
private static int getCounter(Context context) {
SharedPreferences prefs = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try {
return prefs.getInt("count", 0);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
These methods will make your work easy and you just have to pass the incremented value to saveCounter for saving the value and then for getting the value use getCounter
Dear archana,
Please save the varible/flag in SharedPreferences. Check varialble value (whether 5) then increment on every execution of activity until 5 and save to sharedprefrences and get it from there with every launch of activity.
In oncreate method of activity please update the variable with increment+1 and save it and check it in next launch
For more visit:
http://www.tutorialspoint.com/android/android_shared_preferences.htm
Thanks
Initialize your counter to 0 and increment it in onCreate() and onResume() methods of your activity. As soon as you increment these values, store these values in Shared Prefrences(as described in above answer). If you have trouble using Shared Preferences, try TinyDB, it is based on Shared Preferences and is much easier to handle.
I'm creating a shared preference in my MainActivity and then I want to get a value saved in the shared preference in my IntentService; however; I keep getting the default value rather than the value that I had saved.
This is my code to create the SharedPreference in my MainActivity:
SharedPreferences prefs = this.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
prefs.edit().putString("inter", inter).apply();
And in my IntentService class:
protected void onHandleIntent(Intent intent) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
final String inter = preferences.getString("inter", "default_no");
}
The problem here is a subtle one:
SharedPreferences.Editor#commit stores the modifications to storage in a blocking fashion, so you are guaranteed that any other instance that queries the value on the same thread will actually get the new one.
SharedPreferences.Editor#apply does so asynchronously so if you fetch the value on another instance of SharedPreferences too fast, it might not get the updated value.
Commit may actually work better on your situation as you are not doing any big change to the preferences. If you need to use apply, you might want to induce a slight delay using Handler#post.
Cheers.
Try using and editor to save your value in SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
SharedPreferences.Editoreditor = pref.edit();
editor.putString("inter", inter);
editor.commit();//This will make your value store in SharedPreferences
I'm trying to make a custom preferenceDialog which has four radioButtons, I would like to save the selected radiobutton with a diferent String and persist the value. Whe the dialog reopens, recover the string, compare and check the matched radiobutton.
I've tried persistance functions but I'm not able to achive it..
Can someone help me please?
How about using SharedPreference to persist values?
Code Example:
// Gets SharedPreference with private mode
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
HARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
// Saves int values
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(KEY_NAME, value);
editor.commit();
// Gets int values
sharedPref.getInt(KEY_NAME, defaultValue);
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