Android get string name from resource file values.xml - android

I would like to get name from values resource file.
for example
values.xml
<string name="ind_ginger">Ginger</string>
<string name="ind_garlic">Garlic</string>
I am using them for the check boxes like
<CheckBox
android:id="#+id/c01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="21dp"
android:text="#string/ind_garlic"
android:layout_alignTop="#+id/c02"
android:layout_alignRight="#+id/saveChanges"
android:layout_alignEnd="#+id/saveChanges" />
<CheckBox
android:id="#+id/c02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="81dp"
android:layout_marginStart="81dp"
android:checked="false"
android:text="#string/ind_ginger"
android:visibility="visible"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp" />
In application I need access String Name ( Please note value)
for (CheckBox item : checkBoxList){
if(item.isChecked())
{
//String text=item.getText().toString();String viewID = getResources().getResourceName(item.getId()); // gets me the name
String name = getResources().getResourceEntryName(item.getId());
String tName =
//item.getText().toString();
// String id = item.getTag().toString();
Toast.makeText(getApplicationContext(), tName,Toast.LENGTH_SHORT).show();
Log.d(viewID, TAG);
}
}
Is parsing the XML only way?

Try
String ginger = getResources().getString(R.string.ind_ginger)

Easiest way to get the "KEY" name is as following:
Log.e("KEY_NAME", getResources().getResourceEntryName(R.string.app_name));
Here you will get "app_name" as result.
This can be also help in support multi-language support feature.

You can use this to fetch all the String Keys in string.xml
Field[] fields = R.string.class.getFields();
String[] allStringNames = new String[fields.length];
for (int i =0; i < fields.length; i++) {
allStringNames[i] = fields[i].getName();
Log.e("String Key Name",""+allStringNames[i]);
}
Hope this will help

Just Store you string items in (And its better if you store your string file in in strings.xml and not value.xml )
strings.xml
<string name="ind_ginger">Ginger</string>
<string name="ind_garlic">Garlic</string>

Firstly if you need ind_ginger you need to change your code from this
<string name="ind_ginger">Ginger</string>
to
<string name="ind_ginger">ind_ginger</string>
and
String ginger = getResources().getString(R.string.ind_ginger)
to get the ind_ginger.
But what I can see from your code is you are using .getResourceEntryName(item.getId()) for that you need to create a String arraylist which would have all the itemId from strings.xml and then you can use them with item.get(position).
Here position is the position of the item in your array list.

Related

Can't get rupee symbol to show correctly from strings.xml

So this works fine:
strFoo = "\u20B9" + strBar
But this doesn't
strFoo = R.string.rupee_symbol.toString() + strBar //.toString() is required
//R.string.rupee_symbol.toString() evaluates to some random number 2131755148... which I believe is a character array...
strings.xml
<string name="rupee_symbol">\u20B9 </string>
I can't figure out why it would behave like that, it looks like the same thing...!
You should not concatenate strings with string resources instead, you can use place holder:
<string name="rupee_symbol">\u20B9%s</string>
And use:
strFoo = resources.getString(R.string.rupee_symbol, strBar)
use getString(R.string.rupee_symbol) instead R.string.rupee_symbol.toString()
For example-
String strBar = String.valueOf(100);
String strFoo = getString(R.string.rupee_symbol)+strBar;
textView.setText( strFoo);

How to use two strings in a layout?

I try to make a simple app and I used two strings in strings.xml:
<string name="question">is the capital of:</string>
<string name="riga">Riga</string>
And I want to add them to one text view.
I want the output to be (Riga is the capital of: ).
How can I do this?
This is my layout:
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/riga" + "#string/question"
/>
You cannot do this in XML. You could do it in Java, however. Assuming you're inside an Activity:
String riga = getString(R.string.riga);
String question = getString(R.string.question);
TextView tv = findViewById(/* your id here */);
tv.setText(riga + question);
Even better would be to use format arguments in one of your strings:
<string name="question">%1$s is the capital of:</string>
And then do this in your activity:
String riga = getString(R.string.riga);
String fullQuestion = getString(R.string.question, riga);
TextView tv = findViewById(/* your id here */);
tv.setText(fullQuestion);

Decimal Amount Format Issue-Android

Declaration :
DecimalFormat mAmtFormat = new DecimalFormat("##,##,##,##0.00");
edtAmounts = (EditText) findViewById(R.id.txtAmounts);
From xml File Edit text as
<EditText
android:id="#+id/txtAmounts"
android:layout_height="50dip"
android:layout_marginLeft="10dip"
android:background="#FFFFFF"
android:gravity="center_vertical"
android:inputType="numberDecimal"
android:singleLine="true"
android:textSize="18dip"
android:textStyle="bold"
android:width="170dip" />
From Back End mCurtotamt is 565656565(double)
Fetching Data From Sqlite DataBase:
edtAmounts.setText(String.valueOf(mAmtFormat.format(mDoubleformat
.parse(mCurtotamt).doubleValue())))
but the value set into the edit text as 56,56,57,000.00
what is happening over here.
When you get the value from the back end, do not get it as a String like this:
String mCurtotamt = cursor.getString(cursor.getColumnIndex("column_name"));
Instead, get it as a double directly, like this:
double mCurtotamt = cursor.getDouble(cursor.getColumnIndex("column_name"));
Then you don't need to parse it when you set the edit text, but can format it directly:
edtAmounts.setText(String.valueOf(mAmtFormat.format(mCurtoamt)));
The problem is being introduced when converting it to a String when you call cursor.getString().
Use this one for indian format like this "##,##,##0.00" :
static public String formatCurrency(Double doubleVal) {
return new DecimalFormat("##,##,##0.00").format(doubleVal);
}
This function return the value in correct given format. If you pass 5555555.00 value then function return 55,55,555.00 as a string.

android replace delimeter with newline

I have a string which has delimiter in it. I want to know the best way to replace the delimiter with a new line. I have had various issues with using the String Tokenizer the main problem being NoSuchElementException. Basically my approach thus far is to retrieve data from a database Once this has been achieved I store each of the records in a string String question = c.getString(1);
Here is the string tokenizer StringTokenizer st = new StringTokenizer(question,"<ENTER>"); I loop through the tokens using a while loop
while (st.hasMoreTokens()) {
System.err.println(st.nextToken());
// quest.setText(String.valueOf(st.nextToken("<ENTER>")));
}
Working example in code
String in = "What is the output of: <ENTER><ENTER>echo 6 % 4;";
in=in.substring(in.indexOf("<ENTER>")+7,in.lastIndexOf("<ENTER>"));
String[] mSplitted= in.replaceAll("<ENTER><ENTER>", "<ENTER>").split("<ENTER>");
for(int i=0;i<mSplitted.length;i++)
{
System.out.println("values: "+mSplitted[i]);
quest.setText(String.valueOf(mSplitted[i]));
}
xml code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/quest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="false"
android:text="TextView" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.08"
android:text="#string/hello" />
<Button
android:id="#+id/Next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
output
can't you use split() of String.
String in = "<ENTER>title=Java-Samples<ENTER>" +
"<ENTER>author=Emiley J<ENTER>" +
"<ENTER>publisher=java-samples.com<ENTER>" +
"<ENTER>copyright=2007<ENTER>";
in=in.substring(in.indexOf("<ENTER>")+7,in.lastIndexOf("<ENTER>"));
String[] mSplitted= in.replaceAll("<ENTER><ENTER>", "<ENTER>").split("<ENTER>");
String mFinal="";
for(int i=0;i<mSplitted.length;i++)
{
System.out.println("values: "+mSplitted[i]);
mFinal= mFinal+ mSplitted[i];
}
quest.setText(mFinal);
The reason behind NoSuchElementException is that you are checking whether your Tokenizer has more tokens, but if it does, then you are reading two tokens at the same time.
Documentation says hasMoreTokens tests if there are more tokens available from this tokenizer's string.
If this method returns true, then a subsequent call to nextToken() with no argument will successfully return a token.
That means hasMoreTokens is only sure about the next token but not the token next to that!
Your condition should be..
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val="";
if(st.hasMoreTokens())
val = st.nextToken();
System.out.println(key + "\n" + val);
}
As your condition will work for only even number of elements.

android: referring to ressources in custom xml

i have a multilingual android app, where i have put the different translations in the strings.xml in the respective directory.
now i also have a custom xml file, where i would like to reference texts like this:
<?xml version="1.0" encoding="UTF-8"?>
<rooms>
<room title="#+string/localizedtext" />
</rooms>
now when i read the title attribute in my code, i obviously get the unresolved string "#+string/localizedtext" like it is.
is it possible to somehow resolve this link to the localized text automatically?
thanks!
Almost a year later:
public static String getStringResource(Context context, String thingie) {
try {
String[] split = thingie.split("/");
String pack = split[0].replace("#", "");
String name = split[1];
int id = context.getResources().getIdentifier(name, pack, context.getPackageName());
return context.getResources().getString(id);
} catch (Exception e) {
return thingie;
}
}
That'll do it.
This might seem like a broad answer but I believe it'll clarify a lot of things for people who spent hours looking for it (I'm one of them).
The short answer is yes, you can use references in custom XML, not just for strings, but that's the example I use, for ease of understanding.
Considering the context:
res/values/strings.xml
(Default strings, usually en-US for convenience but that's up to the developer)
<resources>
<string name="sample_string">This is a sample string.</string>
</resources>
res/values-fr/strings.xml
(Localized french strings)
<resources>
<string name="sample_string">Ceci est un exemple de chaƮne</string>
</resources>
res/xml/test.xml
(Custom XML file)
<!-- #string/sample_string identifies both
the default and french localized strings,
the system settings determine which is used at runtime.
-->
<test>
<sample name="sampleName" text="#string/sample_string"/>
</test>
src/com/example/app/TestXmlParser.java
//Omitted imports for clarity.
public class testXmlParser {
public static final String ns = null;
public int parse(XmlResourceParser parser) throws XmlPullParserException,
IOException{
while(parser.next() != XmlPullParser.END_DOCUMENT){
if(parser.getEventType() == XmlPullParser.START_TAG){
if(parser.getName().equalsIgnoreCase("sample")){
// This is what matters, we're getting a
// resource identifier and returning it.
return parser.getAttributeResourceValue(ns, "text", -1);
}
}
}
return -1;
}
Use String getText(int id) to obtain the string corresponding to id (localized, if available).
Using the example above it would amount to replace :
//Return the resource id
return parser.getAttributeResourceValue(ns, "text", -1);
with :
//Return the localized string corresponding to the id.
int id = parser.getAttributeResourceValue(ns, "text", -1);
return getString(id);
The way you tried is not possible.
You might get similar functionality with <string-array> resource:
<resources>
<string-array name="room">
<item>#string/localizedText</item>
<item>#string/otherLocalizedText</item>
</string-array>
</resources>
then you would use it like this :
String[] room = getResources().getStringArray(R.array.room);
String localizedText = room[0];
String otherLocalizedText = room[1];
Localization in Android is done with resource identifiers. Check out this Android tutorial.
http://developer.android.com/resources/tutorials/localization/index.html
See discussion below.
Great answer kyis, shame I still don't have enough brownie points to rate it. To answer Nick's question, just change the last bit of code to:
int id = parser.getAttributeResourceValue(ns, "text", 0);
return (id != 0) ? getString(id) : parser.getAttributeValue(ns, "text");
Note that I used 0 for the default value of the resource as this is guaranteed never to be a real resource value. -1 would have done also.

Categories

Resources