Shared Preferences issue, not freeing the value after calling clear - android

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

Related

How to pass values to another class without using startActivity()

How can I send values to another class without opening it immediately ?
It's like I want to save that value first in another class and I will use that value later.
use SharedPreferences
Example:
SharedPreferences sharedpreferences = getSharedPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("YOUKEY", "YOUR VALUE WANT TO SAVE");
editor.apply(); //OR editor.commit() -_-
to retrieve it
String name = sharedpreferences.getString("YOURKEY",null);

How do I get SharedPreference object in FragmentStatePagerAdapter?

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.

Not getting saved SharedPreference value from IntentService

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

Custom PreferenceDialog persistString

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

SharedPreferences

I'm creating a SharedPreferences and it's working only if I start Activity like this:
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
But my SharedPreferences is not working after I save it and hit back a few times, to go at menu page and go to the page where I want to get my preferences.
Anyone can help me with that?
Code below:
This is where I save my preferences:
String MYPREFS = "MyPref";
SharedPreferences mySharedPreferences;
SharedPreferences.Editor myEditor;
Inside onCreate:
mySharedPreferences = getSharedPreferences(MYPREFS,0);
myEditor = mySharedPreferences.edit();
Inside button onClickListener:
myEditor.putString("address", AddressET.getText().toString());
myEditor.putString("contact", ContactET.getText().toString());
myEditor.commit();
Intent myIntent = new Intent(myContext, nok_individual_particular.class);
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
This is the activity I pass to:
SharedPreferences mySharedPreferences;
Inside onCreate:
Intent myReceivingIntent = getIntent();
String myPREFName = myReceivingIntent.getStringExtra("prefName");
mySharedPreferences = getSharedPreferences(myPREFName, 0);
applySavedPreferences();
In the applySavedPreferences method:
String addressValue = mySharedPreferences.getString("address", "Jack Smith");
String contactValue = mySharedPreferences.getString("contact", "Jack Smith");
addressTV.setText(addressValue);
contactTV.setText(contactValue);
SharedPreferences: This is how it works
To save your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString("valueName", "value");
editor.commit();
To retrieve your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
String strMyData = sPrefs.getString("valueName", "default value");
The example above is how to set a string and retrieve it.
You are not using SharedPreferences. In your example, you are passing an extra to an activity, but this only makes available the value to the new activity, it doesn't save the value to SharedPreferences.
To use SharedPreferences, you have to do the following:
Save
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("prefName", "String to save").commit();
Get
String value = PreferenceManager.getDefaultSharedPreferences(this).getString("prefName"), "default value");
After mySharedPreferences.edit();
mySharedPreferences.commit();
should be your last line. This enables u to save and close the SharedPreferences file you have edited.
Well, you don't need to pass the sharedprefs in an intent and all. It will be available throughout your application in all activities.
Just call SharedPreferences my_prefs= getSharedPreferences("Pref_name", 0); and then u have a reference to that SharedPreferences file and then u can retrieve values from it.
I prefer using SharedPreferences to save my data and use it throughout my classes , plus they will be saved to the device , making them available even after the app is killed ... Here is an example for ya !
//Some String that I should remember, I am just using the package name for now
String app = this.getPackageName();/*This is going to be used more like a file to save my stuff to*/
//Setting our sharedpreferences
SharedPreferences sha = sha = getApplicationContext().getSharedPreferences(app, SherlockActivity.MODE_PRIVATE);
String myString = "This is the String that you want to save so you can use among your classes"
//Now we call in an editor for that SharedPreferences so we can write and delete stuff from it .
Editor edit = sha.edit();
//Now we insert our String.
edit.putString("Something_you_can_remember" , myString);//You will need the "Something_you_can_remember" a few lines ahead , so remember it !
edit.apply(); //Or we can use edit.commit() , but I prefer apply()
//Now our String is saved ! So lets read it !
String whatever = sha.getString("Something_you_can_remember" , "The String incase myString didn't even exist , saves you from a NullPointerException");
//Here we go ! Now we have our String saved and can be readable among the classes !
//Also , if you wanted to delete that String or whatever you "put" in there , you can call
edit.remove("Something_you_can_remember"); //or edit.clear() to remove all the values stored !
Hope this helps !
Save
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("valueName", "String to save");
sedt.commit();
Get
SharedPreferences sp = getSharedPreferences("key", 0);
String valueName = sp.getString("valueName","");
You do not need to pass SharedPrefences through intents, as SharedPreferences are available to the whole application and any activity has access to it.
You can refer to below example:
Either create SharedPreferences by giving them your choice of name:
SharedPreferences pref = getSharedPreferences("MyPref", MODE_PRIVATE);
OR use default SharedPreferences:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Use your preference file anywhere in your code by getting them through any of the above methods. No need to pass to different activities.
Once you call any of the above method, if the preference file of that name does not exist for your application, android will create one for you.

Categories

Resources