I want to make my app settings with multi language support. Value of settings item will be different in each language. I have string array:
<string-array name="syncTemperature">
<item>#string/celcius</item>
<item>#string/fehrenheit</item>
</string-array>
Which is used in:
<ListPreference
android:key="prefTempUnit"
android:entries="#array/syncTemperature"
android:summary="#string/pref_temp_current"
android:entryValues="#array/syncTemperature"
android:title="#string/pref_temperature" />
and when I will call:
String celcius = sharedPrefs.getString("prefTempUnit", "Celcius")
I will get different value everytime.
My question is how to have one value for all strings under one item.
For example when I want to check what user choose and make some action after.
Like this:
if(prefTemUnit==celcius){
setTempUnitToCelc();
}
EDIT:
For now I figured out one option:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String unit=sharedPrefs.getString("prefTempUnit", "Celcius");
String[] stringArray = getResources().getStringArray(R.array.syncTemperature);
if(unit.equals(stringArray[0])){
//mymethod
}
but I dont know if its the proper one.
Okay I got your solution:
First of all:
String celcius = sharedPrefs.getString("prefTempUnit", "Celcius") will return "Celcius" as a default value. Maybe you should remove it?
Second:
If you would like to access the String value according to the actual language, you should use:
String retrievedValueFromStringXML = getResources().getString(R.string.celcius);
To add:
ListPreference has a method called getValue(), you should use it as well to retrieve the actual value.
Related
such as:
strings.xml:
<resource>
<string name="my_title">Train Video</string>
</resources>
i use this string in Java code many cases, such as:
String title = resources.getString(R.string.my_title) // title="Train Video"
textView.setText(title)
Now i get the new string valued "Train Video Demo" from server, i want to update the strings value so that when i using the following code to get new string:
String title = resources.getString(R.string.my_title) // title="Train Video Demo"
if i can't change Java code, how can i achieve it?
i know Facebook Android App can do it dynamically, i don't know it's program. Is there some blogs to explain this?
so you want to change value dynamically for that you can add %1$s in your string file
string.xml
<resource>
<string name="my_title">Title: %1$s</string>
</resources>
Activity.kt
resources.getString(R.string.my_title, title)
Here the title is dynamic value can be from API or static list.
you can't change the values in strings.xml, so you should just start off by getting all the values you need from the server to begin with, then you can cache those by using a database, you could even use a pre-populated database when releasing your app, then read those values out of the db when you need them. to update your values, make an api call, check if there are new values available, update your local db, app continues to work as normal
You can set the value of textview directly to the string you got.
textView.setText("Train Video Demo")
App version 2.3.3
Here is what i am looking for...
I have few strings in "values/strings.xml". I wish to retrieve the values depending on the string's "name" attribute and use it my application. The input to which string in the xml should be used comes dynamically. Here is an example...
My input from other file :: "A" => This value changes. It can be any value in A,B,C,D.
I have different strings in strings.xml, like...
<string name="A">AforApple</string>
<string name="B">BforBall</string>
<string name="C">CforCat</string>
<string name="D">DforDog</string>
Now, how do i programmatically get the value(AforApple) of the String with name="A".
String str = context.getResources().getString(R.string.A)
or u can use
textBox.setText(R.string.A);
do not forget to import the package com.yourpackackage.R.
You need to use getResources() method:
String a = getResources().getString(R.string.A);
Just for the record, you can also dynamically generate it using reflection.
int stringRes=R.string.class.getField("Here you put the dynamically generated input, such as A").getInt(null);
textView.setText(stringRes);
This will return the resource int value from string XML based on the input, as long as the input value "A" matches string name in the XML, this will retrieve them dynamically.
To access a String resource/value that you’ve defined in an XML file from your Android/Java code, use the Android getString method, like this:
String A = getString(R.string.a_string);
If your code gets a string like "A" and you are trying to dynamically find the string in your resources that matches that name, I don't think you can do that.
Instead of using the strings.xml, you might want to use arrays.xml and build a HashMap from that before you need to access those strings
Try this:
String word = getResources().getString(R.string.A);
Check out the link here.
You can use this code:
getText(R.string.A);
Basically, you need to pass the resource id as a parameter to the getText() method.
I'm new to this but I'm trying to take user input (i.e. userName) and then display it in a different activity via a textView (i.e. display will show "it's 'userName's move").
I'm not sure if I can do this by assigning the user input to a string in the java file, then passing the data with my intent or if I have to use some form of storage.
either way, I'm still confused as to how I can get this back to a string in the .xml file to be displayed.
Any help would be much appreciated :)
cheers
As it was pointed in the comments, you should understand the what an Intent is. You can read about them here. As a very brief example:
Intent launchNewActivity = new Intent(this, NewActivity.class);
launchNewActivity.putExtra("Some key", "Some value"); //sometimes you want to pass extra data
startActivity(launchNewActivity);
Also, it would be good too to understand the use of strings.xml, as explained here. Basically, it is used to define constants that will not be hard-coded and you can call in your code. They help you to keep your code organized and also helps to translate your applications to other languages with ease. Again, a simple example is shown below:
<resources>
<string name="OK">OK</string>
<string name="cancel">Cancel</string>
<!-- Validation error messages for EditText -->
<string name="editText_validation_error_empty_field">The field cannot be empty.</string>
<string name="editText_validation_error_numbers_only">Only numbers are allowed on this field.</string>
</resources>
I think the best way is to use the SHARED PREFERENCES. its exactly for things like that.
thats how you do it:
SharedPreferences prefs = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor prefs.edit();
now, every time you want to change the string you do:
editor.putString("user_name", "jon").commit();
the "user_name" is the name of the string, and the "jon" is the content. so you can save first and last name like this:
editor.putString("user_name", "jon")
editor.putString("last_name", "dow").commit();
dont foget to put the "commit()" at the end.
and every time you want to get the string you can use:
String Name = prefs.getString("user_name", "");
String LastName = prefs.getString("last_name", "");
the good thing about this is that it is saved. so, the next time the user open the app you can still get the strings without making the user put it again by using this again:
String Name = prefs.getString("user_name", "");
String LastName = prefs.getString("last_name", "");
its that simple. hope you got it.
i had some items in my strings.xml file that i want to change programatically, and originally i was doing it through a setText();call but now i am attempting to translate my app to a different language which means everything needs to be set in my strings.xml file. is it possible to put all the text for my app into a strings.xml and change things programatically through references to the string names, instead of using the setText() function call? for example how would i reference "GrandTotal"?
<string name="GrandTotal">Grand Total:</string>
<string name="choose_prompt">Choose a Mode</string>
You can use setText(R.string.GrandTotal);
If you don't have the possibility to set the text via resId directly you can use getString(R.string.GrandTotal);
To avoid confusion between resourceIds and real ints, you could also use statements like
String s = getResources().getString( R.string.grand_total );
but for most ui methods an overload often provides support for passing directly resourceIds as #Keyboardsurfer said
Try this way . I hope it helps you .
setText(getResources().getString(R.string.GrandTotal));
in an Acrivity:
String str = getString(R.string.choose_prompt);
or
String str = this.getString(R.string.choose_prompt);
I have preferences where you can enable/disable what items will show up on the menu. There are 17 items. I made a string array in values/arrays.xml with titles for each of these 17 items.
I have preferences.xml which has the layout for my preferences file, and I would like to reference a single item from the string array to use as the title.
How can I do this?
In the Android developer reference, I see how I can reference a single string with XML, but not how I can reference a string from an array resource in XML.
In short: I don't think you can, but there seems to be a workaround:.
If you take a look into the Android Resource here:
http://developer.android.com/guide/topics/resources/string-resource.html
You see than under the array section (string array, at least), the "RESOURCE REFERENCE" (as you get from an XML) does not specify a way to address the individual items. You can even try in your XML to use "#array/yourarrayhere". I know that in design time you will get the first item. But that is of no practical use if you want to use, let's say... the second, of course.
HOWEVER, there is a trick you can do. See here:
Referencing an XML string in an XML Array (Android)
You can "cheat" (not really) the array definition by addressing independent strings INSIDE the definition of the array. For example, in your strings.xml:
<string name="earth">Earth</string>
<string name="moon">Moon</string>
<string-array name="system">
<item>#string/earth</item>
<item>#string/moon</item>
</string-array>
By using this, you can use "#string/earth" and "#string/moon" normally in your "android:text" and "android:title" XML fields, and yet you won't lose the ability to use the array definition for whatever purposes you intended in the first place.
Seems to work here on my Eclipse. Why don't you try and tell us if it works? :-)
Maybe this would help:
String[] some_array = getResources().getStringArray(R.array.your_string_array)
So you get the array-list as a String[] and then choose any i, some_array[i].
The better option would be to just use the resource returned array as an array,
meaning:
getResources().getStringArray(R.array.your_array)[position]
This is a shortcut approach of other mentioned approaches but does the work in the fashion you want. Otherwise Android doesn't provide direct XML indexing for XML based arrays.
Unfortunately:
It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.
It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.
What I want to accomplish:
I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.
Here's the code I was hoping would complete this task:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1);
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);
for (int i = 0; i < 16; i++) {
if (prefs.getBoolean("itemKey[i]", true)) {
itemsArrayList.add(itemNames[i]);
}
}
What I did:
I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.
To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.
Here's the new code:
for (int i = 0; i < 16; i++) {
if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {
itemsArrayList.add(itemNames[i]);
}
}
Another way of doing it is defining a resources array in strings.xml like below.
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE resources [
<!ENTITY supportDefaultSelection "Choose your issue">
<!ENTITY issueOption1 "Support">
<!ENTITY issueOption2 "Feedback">
<!ENTITY issueOption3 "Help">
]>
and then defining a string array using the above resources
<string-array name="support_issues_array">
<item>&supportDefaultSelection;</item>
<item>&issueOption1;</item>
<item>&issueOption2;</item>
<item>&issueOption3;</item>
</string-array>
You could refer the same string into other xmls too keeping DRY intact.
The advantage I see is, with a single value change it would effect all the references in the code.
The answer is quite easy to implement.
String[] arrayName = getResources().getStringArray(R.array.your_string_array);
and now you can access any element of the array by index (let suppose i'th index), then you can access it by arrayName[i]
I hope you understand this