I am reading shared preferences like
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
and then with preferences.getString("list_of_text_modes", "0") i can get value of any shared preferences. In my example (0 or 1)
Is it possible to get title too, not just value?
For example. I am using ListPreference.
<ListPreference
android:entries="#array/list_of_text_modes"
android:entryValues="#array/list_of_text_mode_values"
android:key="list_of_text_modes"
android:summary=""
android:title="#string/title_language_mode"
android:defaultValue="default" />
<string-array name="list_of_text_modes">
<item>Default</item>
<item>Settings</item>
</string-array>
<string-array name="list_of_text_mode_values">
<item>0</item>
<item>1</item>
now i get "0" if i choose "Default". Can i read somehow title "Default". Or with preferences i can read only values?
And what if I don't have 0 and 1. What if i save as "text1" and "tetx2". Can i read by key, value pair?
You can extract titles from your resources, if you have title index. Try this code:
CharSequence[] titles = context.getResources().getTextArray(R.array.list_of_text_modes);
String myTitle = titles[titleIndex];
You can only get the value. If you have a look at the actual shared preferences file which you can pull from the DDMS -> Data - Data -> Package name. You will see only the value and the key is stored and not the title.
But it is not really a problem because you have it already in your array.
Good luck
I was trying to figure this out as well. Too late for the original question, but I came up with a variation on Hit's answer. For arrays where both the title and value are strings it's not simple to find the index.
<string-array name="sound_keys">
<item>Gong1</item>
<item>Gong2</item>
</string-array>
<string-array name="sound_values">
<item>gonghi</item>
<item>gongmid</item>
</string-array>
But since the value is known you can search the value array and get the index that way, and use that to get the title from it's array. I have a function that does something like this:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String prefValue = sp.getString("sound_values", "some default");
// the arrays used by the ListPreference
CharSequence[] keys = getApplicationContext().getResources().getTextArray(R.array.sound_keys);
CharSequence[] values = getApplicationContext().getResources().getTextArray(R.array.sound_values);
// loop and find index...
int len = values.length;
for (int i = 0; i < len; i++) {
if (values[i].equals(prefValue)) {
return (String) keys[i];
}
}
// if not found use some default value
Related
I have a long string array list of "Animals" that I need to associate a code number with.
Once the "Animal" is selected via my spinner the value is stored in a variable. I also want to have the associated code number stored in its own variable.
How do I go about creating this "pairing" without writting a ton of if/then code. Can I do anything within my strings.xml file that contains my string-array?
<string-array name="Animals">
<item>Dog</item>
<item>Cat</item>
<item>Mouse</item>
...
"Dog" paired with code: "111"
"Cat" paired with code: '222"
"Mouse" paired with code:"333"
You can create the corresponding integer-array and zip them together. There is one BIG WARNING with this though, you have to make sure that if you change one of the arrays, you must update the other too!
Kotlin playground example:
fun main() {
val stringArray: Array<String> = arrayOf("Dog", "Cat")
val intArray: Array<String> = arrayOf("1", "0")
print(sArray.zip(iArray))
}
If the corresponding code is going to be only their index in the array it's simple as:
arrayOf("Dog", "Cat").mapIndexed { index, animal -> index to animal }
So with your example it would be something like this:
<string-array name="Animals">
<item>Dog</item>
<item>Cat</item>
<item>Mouse</item>
...
</string-array>
<integer-array name="AnimalsNumberCodes">
<item>111</item>
<item>222</item>
<item>333</item>
...
</integer-array>
val listOfPairs = resources.getStringArray(R.array.Animals)
.zip(
resources.getIntArray(R.array.AnimalsNumberCodes).toTypedArray()
)
To address the change in the question. All you have to do to get that lookup is to change to a map.
spinnerMap = resources.getStringArray(R.array.Animals)
.zip(
resources.getIntArray(R.array.AnimalsNumberCodes).toTypedArray()
).toMap()
spinnerMap["Dog"] // "111" or whatever you zip it with
Im trying to pull individual strings from a string array at random, and display it on screen(in android studio). But i cant seem to find a solution anywhere.
Its a simple string array, and i need to pull one at a click of a button. My string array is pretty standard and set up like this:
<string-array name="string_array1">
<item>Sentence 1</item>
<item>Sentence 2</item>
</string-array>
You can user java String array or ArrayList of String in Activity like:
Java String Array Example in Activity :
1)define an Array
String string_array1[]={"Sentence 1","Sentence 2"};
Get value from the array :
Sting zeroIndexValue=string_array1[0];
Sting oneIndexValue=string_array1[1];
2) ArrayList Example:
define ArrayList of String:
ArrayList<String> string_List=new ArrayList<String>();
Add value to List:
string_List.add("Sentence 1");
string_List.add("Sentence 2");
Get value from List:
string_List.get(0);
string_List.get(1);
fetch array from string file
String[] string_array1 = getResources().getStringArray(R.array.string_array1);
Now generate random value and fetch it from array.
Random rand = new Random()
int Low = 0;
int High = string_array1.length-1;
int value = rand.nextInt(High-Low) + Low; //It will generate random number in the given range only.
String printed_value = string_array1[value];
I am trying to make an application which will forecast the weather data in the next 7 days. I am adding a settings activity in which the user can change the temperature unit to either Fahrenheit or metric.
I have define this as a ListPreference with entries taken from an array with values metric and Fahrenheit as the following,
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<!--location preference:-->
<EditTextPreference
android:key="#string/pref_location_key"
android:title="#string/locTitle"
android:defaultValue="#string/pref_location_default"
android:inputType="text"
android:singleLine="true"
android:summary="enter location"/>
<!--temperature unit preference:-->
<ListPreference android:key="#string/pref_units_key"
android:defaultValue="#string/pref_units_metric"
android:title="Temperature Unit"
android:summary="select a temperature unit"
android:entries="#array/units"
android:entryValues="#array/indx"/>
</PreferenceScreen>
This is the array resource that contains the entries with the indices of these entries,
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="units">
<item>metric</item>
<item>Fahrenheit</item>
</string-array>
<string-array name="indx">
<item>0</item>
<item>1</item>
</string-array>
</resources>
The problem is that when the temperature preference changes what gets stored in the preference variable is the index string value (either "0" or "1") not the entry index value which is Fahrenheit or metric. When I try to check for the units using if statement the app doesn't recognize the units value unless I use the index string instead of the entry string,
Here is where I try to check the unit,
private String formatHighLows(double high, double low, String unitType) {
if (unitType.equalsIgnoreCase(getString(R.string.pref_units_imperial))) {
high = (high * 1.8) + 32;
low = (low * 1.8) + 32;
} else if (!unitType.equals(getString(R.string.pref_units_metric))) {
Log.d(LOG_TAG, "Unit type not found: " + unitType);
}
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
pref_units_imperial contains the string Fahrenheit, but this if statement is not recognized unless it is written as
if (unitType.equalsIgnoreCase ("1")), unitType has been fetched from the shared preferences previously and sent to the method.
Here is the settings class I use,
public class SettingsActivity extends PreferenceActivity
implements Preference.OnPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
// TODO: Add preferences from XML
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
bindPreferenceSummaryToValue(findPreference (getString(R.string.pref_units_key))); //this will find the preference value associated with locKey key and pass it to be saved in the shared preferences
//we are just getting a reference to the preference, we are not fetching any data from it.
}
private void bindPreferenceSummaryToValue(Preference preference) { //receives user preference
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext()) //conetxt from which this is called. (returns all shared preferences in the app, so you need to distinguish
.getString(preference.getKey(), "")); //the key of the setting that has been changed
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]); //get the entries we have specified in the array xml by the indices associated with them
}
} else {
// For other preferences, set the summary to the value's simple string representation.
preference.setSummary(stringValue);
}
return true;
}
}
In this line preference.setSummary(listPreference.getEntries()[prefIndex], it is supposed to get either Fahrenheit or metric, but it seems that it is getting "0" or "1", I want to get the string name of the unit, I've tried to debug the app, but I couldn't know why it is assigning the index value instead of the entry.
Can anyone please help me fixing this problem?
Any help is appreciated.
Thank you.
I want the list of strings present in the strings.xml file.
Does anyone knows how to get it??? One thing I found is it assigns the ids in sequential order inside R.java but how to get the starting id is not clear.
For Example I have 100 Strings in my strings.xml like below and I want to read in at a time not like giving getResources().getString(int id) for individual.
<string name="app_label">Calendar</string>
<string name="what_label">What</string>
<string name="where_label">Where</string>
<string name="when_label">When</string>
<string name="timezone_label">Time zone</string>
<string name="attendees_label">Guests</string>
<string name="today">Today</string>
<string name="tomorrow">Tomorrow</string>
You can declare your strings in res\values\strings.xml file like this.
<string-array name="vehiclescategory_array">
<item>Cars</item>
<item>Bikes</item>
<item>RVs</item>
<item>Trucks</item>
<item>Other Vehicles</item>
</string-array>
In your activity class, you can access them like the following.
String[] categories;
categories=getResources().getStringArray(R.array.vehiclescategory_array);
In the above list, whatever sequence you declare, the same way it is assigned to the array in your activity. Suppose Cars will be assigned to categories[0]. Hope this helps.
Field[] fields = R.string.class.getDeclaredFields(); // or Field[] fields = R.string.class.getFields();
String str = "";
for (int i =0; i < fields.length; i++) {
int resId = getResources().getIdentifier(fields[i].getName(), "string", getPackageName());
str += fields[i].getName() + " = ";
if (resId != 0) {
str += getResources().getString(resId);
}
str += "\n";
}
You will get all codes of strings with its values in "str" variable.
If you want to access all the Strings from the strings.xml file you could use reflection on the R.string class. An example can be found in this answer, you'll just need to replace drawables with strings.
You could declare an integer array with an entry for each string. I did this for an array of colors once, so I imagine it works for strings as well.
res/values/arrays.xml
<integer-array name="app_strings">
<item>#string/app_label</item>
<item>#string/what_label</item>
<item>#string/where_label</item>
<item>#string/when_label</item>
<item>#string/timezone_label</item>
<item>#string/attendees_label</item>
<item>#string/today</item>
<item>#string/tomorrow</item>
</integer-array>
Then in your code, you would loop over the array and use each value as the argument for getString().
int[] stringIds = getResources().getIntArray(R.array.app_strings);
String[] strings = new String[stringIds.length];
for (int i = 0; i < stringIds.length; i++) {
strings[i] = getString(stringIds[i]);
}
The problem is you have to manually update your arrays.xml whenever you modify your string resources, so it's certainly not ideal.
String[] categories = getResources().getStringArray(R.array.stars_array);
List<String> stringList = new ArrayList<>(Arrays.asList(categories));
use this simple one
I want to retrieve the "entries" not the "entryValue" from a shared preference. I am using this and it gets the entryValue:
String notifyInterval = PreferenceManager.getDefaultSharedPreferences(mActivity).getString(ACCUWX.Preferences.PREF_NOTIFY_INTERVAL, null);
Here is the XML and array files:
<ListPreference
android:key="pref_temp_notifications"
android:title="#string/notifications"
android:entries="#array/pref_temp_notifications"
android:entryValues="#array/pref_temp_notifications_values"
android:dialogTitle="#string/notifications"
android:defaultValue="2"/>
<string-array name="pref_temp_notifications">
<item>#string/my_current_location</item>
<item>#string/home_location</item>
<item>#string/off</item>
</string-array>
<string-array name="pref_temp_notifications_values">
<item>0</item>
<item>1</item>
<item>2</item>
</string-array>
So I'd like to retrieve the string value, not the numeric. The numeric is what I get returned and assigned to my variable notifyInterval. How do I grab the text?
You need to use getAll () method which returns Map, from that map, get KeySet which returns entries of shared preference.
Map<String, ?> test = getAll ();
Set keySet = test.keySet();
Iterator<String> keySetIter = keySet .iterator();
while (keySetIter.hasNext()) {
String keyEntry= keySetIter.next();
}