How do I access a value from my Preference? - android

My app contains shared preferences, so in my "Settings-Menu" I can select an item from a list.
In another java file I want to access the value of the selected item.
I failed passing the integer-value through an intent, because the integer is declared in private static, private boolean, and Android Studio tells me, it cannot be refferenced from a static content.
So how can I receive my value from this integer? Thanks in advance :).
Edit: firstival, thanks a lot for that many answers! But as I'm not that much into java I wasn't able to follow your instructions, so I'm going to depict my problem closer.
I'm using androids template "Settings-Activity". In my strings.xml I've got
<string name="Values">Values</string>
<string-array name="pref_example_list_titles">
<item>A</item>
<item>B</item>
<item>C</item>
</string-array>
<string-array name="pref_example_list_values">
<item>01</item>
<item>02</item>
<item>03</item>
</string-array>
In my SettingsActivity.java
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
{...}
In another java file, a fragment "FirstFragment.java I finally want to assign the value from pref_example_list_values to a new integer, called "Vallue2".
So could you please explain me, how I do this, bc I couldn't follow your explainations. Thanks a lot!

As per documentation:
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them.
This means that a single file holds the value, and the preffered way to read and write to it are as following:
SharedPreferences preference = yourContext.getSharedPreferences(yourFileName), Context.MODE_PRIVATE
);
preference.edit().putString(AN_IDENTIFIER, "aValue").apply();
Then to retrieve the value:
SharedPreferences preference = yourContext.getSharedPreferences(yourFileName), Context.MODE_PRIVATE
);
preference.getString(AN_IDENTIFIER,"a default value to use");

Related

Get current ListPreference label from MainActivity

As explained here:
Get Key, not value, of the ListPreference selection - Possible?
and many other places, it is quite easy to access ListPreferences labels from PreferenceActivity.
What I need to do is to read the label corresponding to the current selected from the main activity.
But I can't find a way.
For example, in my main activity I have
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
I would like to use something like:
ListPreference listPreference = (ListPreference) settings.findPreference("list_of_countries");
And then handle it to get current value and label.
Update 01
I tried to handle another way to retrieve the summary (the name of a country in my example) value which I need to say the customer what he selected. I can't give him the code!
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
String stringSummary = preference.getSummary().toString();
String stringKey = preference.getKey().toString();
if (stringKey.equals("list_of_countries")){
MyActivity.countryName = stringSummary;
}
Nothing to do... the OnPreferenceChangeListener is called.... BEFORE the preference change, i.e., when one item is clicked, so what I succeed to retrieve is just the past summary.
I found no way.

Can't Get Shared Preference Value Even Though Values Exist

Any time I try to getInt() from a SharedPreference my app crashes, yet I can iterate through the preferences as a map. For instance, see the starred lines below:
private void loadPref(){
myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
int sf = DEFAULT_VALUE;
Map<String,?> keys = myPrefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
if (entry.getKey().contentEquals("score_format"))
// this works: //*****
sf = Integer.parseInt(entry.getValue().toString()); //*****
}
// but this does not: //*****
// sf = myPrefs.getInt("score_format", DEFAULT_VALUE); //*****
setScoreFormat(sf);
}
Clearly, my prefs are being saved (as evidenced by this sample and working preference screens across multiple activities). I am calling super.onCreate() before trying to access getDefaultSharedPreferences.
What should I be considering to understand why this code is not working? Why would the map work but not the "getInt" method? I did notice that the app would also crash if I tried to cast the key value explicitly... I had to cast it toString first.
What am I missing?
if you don't want to parse, make sure the score you're putting into the intent with putExtra is an int type, not a string.
Looks like object assosiated with score_format key is a String but you are trying to obtain it as int which is a mistake.

android default values for shared preferences

I am trying to understand the SharedPreferences of Android. I am a beginner
and don't know a lot about it.
I have this class I implemented for my app Preferences
public class Preferences {
public static final String MY_PREF = "MyPreferences";
private SharedPreferences sharedPreferences;
private Editor editor;
public Preferences(Context context) {
this.sharedPreferences = context.getSharedPreferences(MY_PREF, 0);
this.editor = this.sharedPreferences.edit();
}
public void set(String key, String value) {
this.editor.putString(key, value);
this.editor.commit();
}
public String get(String key) {
return this.sharedPreferences.getString(key, null);
}
public void clear(String key) {
this.editor.remove(key);
this.editor.commit();
}
public void clear() {
this.editor.clear();
this.editor.commit();
}
}
The thing is that I would like to set default preferences. They would be set when the app is installed and could be modified after by the application and stay persistent.
I heard about a preferences.xml but I don't understand the process.
Could someone help me?
Thanks for you time
Simple, if you want a separate default value for each variable, you need to do it for each one, but on your method:
public String get(String key) {
return this.sharedPreferences.getString(key,"this is your default value");
}
If the variable was never accessed by the user or was never created, the system will set the default value as value and if you or the user changed this value, the default value is ignored. See http://developer.android.com/guide/topics/data/data-storage.html#pref
Directly from the Android Documentation:
The SharedPreferences class provides a general framework that allows
you to save and retrieve persistent key-value pairs of primitive data
types. You can use SharedPreferences to save any primitive data:
booleans, floats, ints, longs, and strings. This data will persist
across user sessions (even if your application is killed).
Could you use the default value parameter of the getX() method?
For example, to get a String called 'username', you could use this:
String username = prefs.getString("username_key", "DefaultUsername");
You can simply define your default values in your Preferences class.
You can store default values in string resource:
<string name="key_name">default_value</string>
and then get it as it follows:
int ResId = context.getResources().getIdentifier(key_name, "string", context.getPackageName()));
prefs.getString(key_name,context.getResources().getString(ResId);

Is there a way i can get a sharedpreference name?

Let's say i created a shared preference.
sp = this.getSharedPreferences("name",MODE_PRIVATE);
If i'm in another activity, is there a way i can find the name of sp and set it to a string?
you can access the sharedpreferences with the same method you have used. use a public static varibale to hold the name in a class.
Use a constant. a public final static String NAME = "the_name";. Then you can alway reference it as NameOfTheClassWhereYouPutIt.NAME
If you are looking to refer to a given shared preference in another activity, you can pass that String key of that preference to the new Activity via its Intent when creating it.
If you simply need to find a certain preference in any activity, you can iterate over all of the preferences, and get access to all the keys (and values) that way.
Assuming your shared preferences is in the variable mySharedPreferences, an example of getting all of the keys and vales would be:
Map<String,?> preferenceMap = mySharedPreferences.getAll();
for ( Map.Entry<String, ?> keyValPair : preferenceMap.entrySet() )
{
String key = keyValPair.getKey(); // this is your preference name
String val = keyValPair.getValue(); // this is your preference value
}

Android shared preference selecting image

I have been making a live wallpaper and have finally succeeded so far, but now I would like to let the users choose the background they would like to have that I have in the drawable folder.
I have been trying a few things but so far no luck passing this through.
I have an xml file to read one of two images they can choose from (I figure if I can get one working they all should be the same)
Here's how it reads so far
"DarkBack"
"MediumBackb"
"LightBack"
<string-array name="frontleft_value">
<item>"1"</item>
<item>"2"</item>
<item>"3"</item>
</string-array>bubble
So they choose from either one of three backgrounds
In the activity I have this:
mPrefs = UnderwaterActivity.this.getSharedPreferences(SHARED_PREFS_NAME, 0);
mPrefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(mPrefs, null);
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
myOtherClass.myfrontleftimage = (Integer.parseInt(prefs.getString("front_sub_left_choice", "1")));
}
So this should get me a integer of 1 or 2 depending on which one is click in the settings of the livewallpaper.
The background image is held in a different class but first I have to compare what they clicked, so I tried an if/else statement to no luck at all.
I tried strings but that didn't work so I changed it to int and had some luck but not all.
The if else went like this.
private int chooseImage(){
int theImage = 0;
if(myfrontleftimage == 1){
theImage = R.drawable.image1;
}else if (myfrontleftimage == 2){
theImage = R.drawable.image2;
}else{
theImage = R.drawable.image3;
}
return theImage;
}
Then I put this method into the background image so it can read it, I have a setting java file and implement the engine for shared preferences also but I have a feeling it's in my if else statement, what I want is to get the value of the preference and compare them if they equal to 1, 2, 3 if either one equals one of them then it loads that background image, makes sense in theory but not in practice obviously, any help would be greatly appreciated, if I can figure this one out then I can use it for sprites also that I have in the livewallpaper.
Thanks in advance
EDIT:
I found the issue so far, I put in the pref file this:
<string-array name="livewallpaper_back_names">
<item>Brown</item>
<item>Grey</item>
</string-array>
<string-array name="livewallpaper_back_value">
<item>0x7f020000</item>
<item>0x7f020001</item>
</string-array>
Then in the sharedpreferences file I try to parse the 0x7f020000 (which I want to use to pick the image with) into an int like so
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key)
{
sackNum = Integer.parseInt(prefs.getString("livewallpaper_back", "0x7f020000"));
}
But then I get this error that it can't be done
E/AndroidRuntime(340): java.lang.NumberFormatException: unable to parse '0x7f020000' as integer
So this is where I am stuck at the moment.
I checked the log and the array does get passed through and changes no problem so this is where the issue lies and if anyone can help me parse this thing into an int I would greatly appreciate it.
Thanks again for any help in advance.
You are listening for Shared preference changes, but you do not appear to be setting them.
Set the charedPreferences using and Editor when the user makes a selection.
Then in your activity, read the shared preference in the onCreate() method. That way it will check the savedPreference every time the activity starts.
The code for editing preferences is something like this:
public void onClick(DialogInterface dialog, int whichButton) {
SharedPreferences settings = getSharedPreferences("YOURPREFERENCENAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", "MyNameIsBob");
editor.putString("password", "MyPasswordIsEasy");
editor.commit();
}
In your onCreate you would do something like this:
// Get any existing username and password saved
// Restore preferences
SharedPreferences settings = getSharedPreferences("YOURPREFERENCENAME", 0);
user_name = settings.getString("name", "defaultNameValue");
password = settings.getString("password", "defaultPasswordValue");
Ok I figured this out with the help of the test pattern example found here: http://www.codeproject.com/KB/android/AndroidLiveWallpaper.aspx
First I add a third depth to the array.xml like
<string-array name="livewallpaper_back_names">
<item>Brown</item>
<item>Grey</item>
</string-array>
<string-array name="livewallpaper_back_value">
<item>brown</item>
<item>grey</item>
</string-array>
<integer-array name="brownback">
<item>0x7f020000</item>
</integer-array>
<integer-array name="greyback">
<item>0x7f020001</item>
</integer-array>
So now it will read the brown or grey then I add the getResources().getIdentifier to get which array the user picks in the settings menu of the livewallpaper like so:
public void onSharedPreferenceChanged(SharedPreferences prefs, String key)
{
String blah;
sackNum = prefs.getString("livewallpaper_back", "brown");
int pid = getResources().getIdentifier(sackNum + "back", "array", getPackageName());
int backImageArray[] = getResources().getIntArray(pid);
int back = backImageArray[0];
int theBackImage = back;
blah = getString(back);
Log.d(TAG, blah);
}
the int pid gathers the array of either brown or grey by adding back (in the xml) and gets the array which I then put into the backImageArray choosing only the first one because thats the only one, next I change the array into an integer (int back = backImageArray[0];) so it can be read to get the image the user chooses which would be theBackImage or you caould just drop it right into the Bitmap as such
private Bitmap _backgroundImage = BitmapFactory.decodeResource(getResources(),theBackImage);
and presto it gets the image. If anyone has a better way of doing this please add to this but so far this works, Mind you you have to update in the code so it reads it and changes it right away but this is the answer I figured out to get the user to at least choose the image.
Hope it helps someone else out.
Sam

Categories

Resources