Custom PreferenceDialog persistString - android

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

Related

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.

Can't access sharedpreferences from other activity?

I have a fragment where I let set some SharedPreference values set.
In the fragment, everything works fine - I can get any value I want, saving, editing, deleting works fine.
Then I have an Activity, from where I want to get the value "savedValue1" - but it does not work
public static final String MyPref = "MyPreference";
static SharedPreferences sharedpreferences;
//onCreateView...
sharedpreferences = this.getActivity().getSharedPreferences(MyPref,
Context.MODE_PRIVATE);
editor.putString("savedValue1", someString);
editor.commit();
I tried it with in Fragment:
public static String getValue(){
return sharedpreferences.getString("savedValue1","");
}
in Activity:
String newValue = Fragment.getValue();
But that doesn't work - any hint?
You should not have a Fragment.getValue() method.
SharedPreferences are here to avoid that.
Use the same getSharedPreferences("whatever", Context.MODE_PRIVATE) code and you shall get/set the same values inside the same preferences.
That is how it is supposed to be used. From the official documentation:
For any particular set of preferences, there is a single instance of
this class that all clients share.
Use this code to save and retrieve values from SharedPreferences
//To save string
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putString("savedValue1", someString);
e.commit();
//Retrieve team score
String saved_value = settings.getString("savedValue1", "");

value is not getting in sharedpreferences, always default value is coming

I am storing one value in sharedpreferences using the below code
SharedPreferences sp;
sp = getApplicationContext().getSharedPreferences("myshare",
MODE_PRIVATE);
Editor e = sp.edit();
e.putString("a","unni");
e.commit();
this is in AddBluetooth Activity
Now I am retrieving that value from another activity called Dashboard Activity, which is using the below code
SharedPreferences sp;
sp = getApplicationContext().getSharedPreferences("myshare",
MODE_PRIVATE);
String aa =sp.getString("a","me");
but its's only returning the default value, how can I fix this issue
IF you're defining your preferences in a preferences.xml you need to access it using SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
// declare this class variable in class from where u will put the string u wanna store in shared pref
//class variables
SharedPreferences pref;
SharedPreferences.Editor editor;
-------------------
//in oncrete method
// declare this in oncreate method
pref = getSharedPreferences("testapp", MODE_PRIVATE);
editor = pref.edit();
// the varibale u wanna put use the below statements
// for string use putString
// for boolean as u need use putBoolean
// have a look at the various option it offers..
editor.putString("selected", "nil");
editor.commit();
// here is the statement use this statement in class where u wanna retireve ur strings
// use getBoolean for Boolean variables
pref.getString("selected", "nil")
// here in sceond parameter in above statement is : if the value u r requesting for that is specified in first parameter is not present then it will return the //value which is your second parameter..
Pull Ur Shared-Pref :
Go to Data-->Data-->Ur package-->Pull The SharedPref file [DDMS]
Actually for me the above code snippet is not working in API 19, but for lower versions its working. So I used,
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor=saved_values.edit();
editor.putString("newCEAAddress", address);
editor.commit();
for getting value
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
DEVICE_ADDRESS=saved_values.getString("newCEAAddress", "nil");

Shared Preferences issue, not freeing the value after calling clear

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

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