How to set the Default Value of a ListPreference - java

i need to set the defult value for a ListPreference when the Activity starts.
I've tried with ListPreference.setDefaultvalue("value"); but it makes the firts Entry of the List as default. I need it because i must check a condition and set as default the value which satisfies that condition, so I think it can't be done from the xml file (with android:defaultValue)
For example, suppose I have this array of values in the arrays.xml:
<string-array name="opts">
<item>red</item>
<item>green</item>
<item>blue</item>
</string-array>
<string-array name="opts_values">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
In the PreferenceScreen xml:
<ListPreference
android:title="Colour select"
android:summary="Select your favourite"
android:key="colour"
android:entries="#array/opts"
android:entryValues="#array/opts_values" />
In the Activity I'd like to do something like this:
String mycolour;
if (something) {
mycolour="1";
} else {
mycolour="2";
}
ListPreference colour = (ListPreference) findPreference ("colour");
colour.setDefaultValue(mycolour);
But it doesn't work, because it makes the first choice as default. Could you explain me how to make another one as default? Thanks.

You don't need to programmatically handle the default value of ListPreferences. You can do this in xml setting file. Below is an example
<string-array name="opts">
<item>red</item>
<item>green</item>
<item>blue</item>
</string-array>
<string-array name="opts_values">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
...
<ListPreference
android:title="Colour select"
android:summary="Select your favourite"
android:key="colour"
android:entries="#array/opts"
android:entryValues="#array/opts_values"
android:defaultValue="2" />
here I selected 2 as a default value. Remember defaultvalue will be opts_values element.

Have you tried:
setValueIndex(int index);

Sorry my bad English.
List item
Retrieve the list Check if the value is null. If it is null set to the default value.
Code:
ListPreference dataPref = (ListPreference) findPreference("keyList");
if(dataPref.getValue() == null){
dataPref.setValueIndex(0); //set to index of your deafult value
}

You can set your default value by using the key like this
<string-array name="syncFrequency">
<item name="1">Block All Calls</item>
<item name="2">Block Black List</item>
<item name="3">Block Unknown Calls</item>
<item name="4">Allow White List</item>
<item name="5">Receive All Calls</item>
</string-array>
<string-array name="syncFrequencyValues">
<item name="1">Block_All_Calls</item>
<item name="2">Block_Black_List</item>
<item name="3">Block_Unknown_Calls</item>
<item name="4">Allow_White_List</item>
<item name="5">Receive_All_Calls</item>
</string-array>
<ListPreference
android:key="prefSyncFrequency"
android:entries="#array/syncFrequency"
android:summary="%s"
android:defaultValue="Block_Black_List"
android:entryValues="#array/syncFrequencyValues"
android:title="#string/call_block_options" />

or you can also try colour.setValue(mycolour);

Just for the record if someone else has this problem:
setValueIndex(int X) is setting the value # index X to the default value - so it is probably what you are looking for.
Set this value AFTER you added the Values! (stupid mistake but took me half an hour)

Actually it's because the SharedPreferences will persist after you re-build the app.
Uninstall it and try again.

((ListPreference) findPreference("pref_language")).setValue(Locale
.getDefault().getLanguage());
setValue() is ListPreference's method, and setDefaultvalue is Preference's method

This is an old post, but here's another way to set the default value for ListPreference with the following line of code:
PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences, false);

Use the xml attribute android:defaultValue="<VALUE>" in your list tag to set the default value.
Note: the <VALUE> is the actual value and not the index of string
array.
If still its not working, try below steps.
Clear application data.
Uninstall and reinstall the app
Check the list preference, you will see the default value selected
Strange, I know but it worked in my case.

If you are using Android Jetpack Preference, known as androidx.preference:preference-ktx:1.1.1 in Kotlin, you can use:
app:defaultValue="<Value_in_string-array_with_values>".
Additionally: defaultValue is not an index number, is the actual value from the values array.
I also recommend using a string resource for the default value and clearing the data, uninstalling the app, or removing the file:
<package_name_in_app_manifest>_preferences.xml in data/data/shared_prefs/<package_name_in_app_manifest>. Replace <package_name_in_app_manifest> with real name like com.example.yourapp.
I was having the same issue and the defaultValue wasn't updating because it already had a wrong default value of "true". Solved it by using the Android Studio File Explorer and deleting the file.
And here is my solution example:
res/xml/root_preferences.xml
<ListPreference
app:key="mic"
app:title="#string/select_mic_title"
app:useSimpleSummaryProvider="true"
app:entries="#array/mic_entries"
app:entryValues="#array/mic_values"
app:defaultValue="#string/default_mic"
 />
res/values/arrays
<!-- Mic Preference -->
<string-array name="mic_entries">
<item>#string/default_mic</item>
<item>Headband</item>
</string-array>

<string-array name="mic_values">

 <item>#string/default_mic</item>
<item>Headband</item>

</string-array>
res/strings.xml
<string name="default_mic">Integrated</string>
Result:
Setting Fragment with default list value of "Integrated" given by string resource #string/default_mic

Related

Android - how to disable / change editTexts 'Pin'

How can I edit or disable the 'pin' for editTexts that appears when marking text? I was able to edit the underline & the cursor, but not that 'pin' because I didn't know how to call it.
Image of the pin (pink) added.
I think the colourAccent influences the colour of that pin, try changing the colour of colourAccent in color.xml
This 'pin' is called "text select handle"
To change it you need to use these attributes:
text_select_handle_left and text_select_handle_right
Add these drawables with customized design/color to your drawable folder and add to style
<style name="MyTheme" parent="#style/MyCustomTheme">
<item name="android:textSelectHandle">#drawable/text_select_handle_middle</item>
<item name="android:textSelectHandleLeft">#drawable/text_select_handle_left</item>
<item name="android:textSelectHandleRight">#drawable/text_select_handle_right</item>
</style>

ListPreference throws NullPointerException

I have a ListPreference:
<ListPreference
android:entries="#array/frequencies"
android:entryValues="#array/frequencies_values"
android:key="pref_key_frequencies"
android:summary="#string/frequency_pref_summary"
android:title="#string/frequency_pref_title" />
#array/frequencies:
<string-array name="frequencies">
<item>5 minutes</item>
<item>10 minutes</item>
<item>15 minutes</item>
<item>20 minutes</item>
<item>30 minutes</item>
<item>60 minutes</item>
</string-array>
#array/frequencies_values
<integer-array name="frequencies_values">
<item>300</item>
<item>600</item>
<item>900</item>
<item>1200</item>
<item>1800</item>
<item>3600</item>
</integer-array>
The elements in the dialog are displayed correctly. However, if I try frequencyListPreference.setValueIndex(0); I get a NullPointerException.
Even if I do nothing in my code, if I click on one of the elements of the list, I get:
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference
If I check the value of one of the elements of the array frequencyListPreference.getEntryValues() is always null.
What am I doing wrong?
To my knowledge, Android will only accept String arrays instead of an Integers.
Change
<integer-array name="frequencies_values">
<item>300</item>
<item>600</item>
<item>900</item>
<item>1200</item>
<item>1800</item>
<item>3600</item>
</integer-array>
To
<string-array name="frequencies_values">
<item>300</item>
<item>600</item>
<item>900</item>
<item>1200</item>
<item>1800</item>
<item>3600</item>
</string-array>
In your code where you read from the Preference, use Integer.parseInt() to convert the value to a usable integer.
See the follow for more detail: ListPreference: use string-array as Entry and integer-array as Entry Values doesn't work

Android [string array] cannot be resolved or is not a field

I'm getting an error about a string array (located in strings.xml) not being able to be resolved.
I've done everything the internet says:
Restarted Eclipse
Deleted my R.java file inside the gen folder
My values folder is still inside the res folder, not moved
None of my XML files have erros
Ran Project -> Clean
I don't have android.R imported in my class.
Checked the R.java class, it indeed doesn't have an app_categories property (my array's name)
The relevant part of the XML:
<string-array name="app_categories">
<item >Cat 1</item>
<item >Cat 2</item>
<item >Cat 3</item>
<item >Cat 4</item>
<item >Cat 5</item>
<item >Cat 6</item>
<item >Cat 7</item>
<item >Cat 8</item>
<item >Cat 9</item>
</string-array>
The Java code:
String[] categoryNames = getResources().getStringArray(R.string.app_categories);
All my other strings are visible. I have another array defined just like this one, and that one isn't visible either.
Exact error below:
app_categories cannot be resolved or is not a field [class_name].java [path] line 45 Java Problem
Just try out this way :
getResources().getString(R.array.app_categories_list);
Instead of R.string use R.array you will get your arraylist.
Don't put your string arrays in strings.xml You must create a new file called arrays.xml and place them there.
And when calling you need R.arrays.myarray, not R.strings.MyArray
After cleaning your project try restarting the adb server by running adb kill-server and adb start-server from the command line
a solution may be to create the R manually:
just hover over the error in the activity file where the problem was and then manually create it, which will cause R to generate the string array you created in strings.xml

Android how to create a nested menulist

I want to create a menulike app where each page is a subcategory of the previous selection and the last page shows the nutrition factor of the selected item, I have already created all the arrays in the arrays.xml :
<string-array name="food_values">
<item>Veggies</item>
<item>Fruits</item>
...
<item>
</string-array>
<string-array name="veg_values">
<item>Cucumber</item>
<item>Celery</item>
...
</string-array>
<string-array name="fruit_values">
<item>Apple</item>
<item>Banana</item>
...
</string-array>
I wanted to create a listview and use set onclicklistener to the list to open the next subcategory but I don't know how to implement it without using a lot of if and else statements and also generating the next listview with the same template list_item.xml.
I also tried Maps but it got too complicated with the nested lists.
Thank you for your help

Getting Booleans and Integers from strings.xml

I've only ever had to work with Strings within the strings.xml file before, but now I have a case where I need to work with Boolean and Integer items.
<item type="integer" name="usenetPort">563</item>
<item type="bool" name="usenetUseSSL">true</item>
I usually use getResources().getString(R.strings.my_string) to retrieve a value, but that doesn't work with Boolean and Integers. I tried getInteger() and getBoolean() but Eclipse says that's wrong.
How do I get the value from Booleans and Integers?
It works for me, first I openned Strings.xml and added this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="integer" name="mynumber">4</item>
</resources>
Then in the code I get the value by doing this:
int number= getResources().getInteger(R.integer.mynumber);
You have to use R.integer.* and not R.string.*
Try this in Activity class
getResources().getInteger(R.integer.some_int_value);
getResources().getBoolean(R.bool.some_bool_value);

Categories