I have a method that returns one of about 20 possible strings from an EditText. Each of these strings has a corresponding response to be printed in a TextView from strings.xml. Is there a way to call a string from strings.xml using something like context.getResources().getString(R.strings."stringFromMethod")? Is there another way to call a string from a large list like that?
The only methods I can think of is converting each string to an int, and use that to find a string in a string array, or a switch statement. Both of which involve a huge amount if-else if statements to convert the string to an int, and would take just enough steps to change if any strings were added or taken away that I'd be more likely to miss one and have fun bug hunting. Any ideas to do this cleanly?
Edit: Forgot to add, another method I tried was using was to get the resourceID from
int ID = context.getResources().getIdentifier("stringFromMethod", "String", context.getPackageName())
and taking that integer and putting it in
context.getResources().getString(ID)
That doesn't appear to be working either.
No, you can't. The getString() requires the resource id in integer format, so you can't append a string to it.
You can, however, try this:
String packageName = context.getPackageName();
int resId = context.getResources().getIdentifier("stringFromMethod", "string", packageName);
if (resId == 0) {
throw new IllegalException("Unknown string resource!"; // can't find the string resource!
}
string stringVal = context.getString(resId);
The above statements will return string value of resource R.string.stringFromMethod.
You need to use reflection (pretty ugly but only solution) load the R class, and get the relevant field by you string and get the value of it.
this is what I used to do in these kind of situations, I will made a Array like
int[] stringIds = { R.string.firstCase,
R.string.secondCase, R.string.thridCase,
R.string.fourthCase,... };
int caseFromServer=getCaseofServerResponse();
here caseFromServer varies from 0 to wahtever
and then simply
context.getResources().getString(stringIds[caseFromServer]);
Related
I want to retrieve few characters from string i.e., String data on the basis of first colon (:) used in string . The String data possibilities are,
String data = "smsto:....."
String data = "MECARD:....."
String data = "geo:....."
String data = "tel:....."
String data = "MATMSG:....."
I want to make a generic String lets say,
String type = "characters up to first colon"
So i do not have to create String type for every possibility and i can call intents according to the type
It looks like you want the scheme of a uri. You can use Uri.parse(data).getScheme(). This will return smsto, MECARD, geo, tel etc...
Check out the Developers site: http://developer.android.com/reference/android/net/Uri.html#getScheme()
Note: #Alessandro's method is probably more efficient. I just got that one off the top of my head.
You can use this to get characters up to first ':':
String[] parts = data.split(":");
String beforeColon = parts[0];
// do whatever with beforeColon
But I don't see what your purpose is, which would help giving you a better solution.
You should use the method indexOf - with that you can get the index of a certain char. Then you retrieve the substring starting from that index. For example:
int index = string.indexOf(':');
String substring = string.substring(index + 1);
Normally, we use R.String.btnClose to get a ID.
Sometings, I hope to use the following code to ID, I know the code is wrong.
I don't know if java support macro var, if so, how can I write code? Thanks!
String s="btnClose"
R.string.s
You may want to try Resources.getIdentifier.
An equivalent for
int id = R.string.btnClose;
would be
int id = getResources().getIdentifier("btnClose", "string", getPackageName());
Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
For example you could have a Map<String, Integer> which returns your id from name.
Inside of activity use this :
String s = getString(R.string.btnClose );
Not in Activity :
public String getText(Context context, int resourceId)
{
Resources resources = context.getResources();
return resources.getString(resourceId);
}
i have string like #string/screen_enable_auto_mode. I know that i can use:
String mess = getResources().getString(R.string.screen_enable_auto_mode);
and i will get a message.
But i have whole string as #string/screen_enable_auto_mode. How can i parse it to
String mess = getResources().getString(R.string.screen_enable_auto_mode);
that i will get a message from xml?
You can use Resources.getIdentifier for this.
int resId = getResources().getIdentifier(
"screen_enable_auto_mode", "string", "com.package.app");
String mess = getResources().getString(resId);
Replace "com.package.app" with the actual package of your app, of course.
I've just noticed that, while most of getters from a Bundle have the possibiliy of including a default value, in case the key doesn't exist in that particular bundle instance, getString does not have that possibility, returning null if that case.
Any ideas on why is that and if there is some way of easy solution to that (by easy I mean not having to check each individual value or extending the Bundle class).
As an example, right now you have only this:
bundle.getString("ITEM_TITLE");
While I would like to do:
bundle.getString("ITEM_TITLE","Unknown Title");
Thanks!
Trojanfoe has the best solution if that is what you want, though once you get into dealing with defaults for other datatypes you'll have to do the same thing for them all.
Another solution would be to check to see if the bundle contains the key:
String myString = bundle.containsKey("key") ? bundle.getString("key") : "default";
It's not as nice as a function, but you could always wrap it if you wanted.
You'll have to wrap it yourself:
public String getBundleString(Bundle b, String key, String def)
{
String value = b.getString(key);
if (value == null)
value = def;
return value;
}
Note: http://developer.android.com/reference/android/os/Bundle.html
public String getString (String key, String defaultValue)
Since: API Level 12
EDIT this function has moved to BaseBundle: here
Another solution is to check for null:
String s = bundle.getString("key");
if (s == null) s = "default";
This is better than csaunders' solution because the Bundle can contain the respective key but it can be of a different type (for example an int), in which case his solution would result myString in being null, instead of "default".
I have a lengthy string in my Android program.
What I need is, I need to split each word of that string and copy that each word to a new String Array.
For eg: If the string is "I did android program" and the string array is named my_array then each index should contain values like:
my_array[0] = I
my_array[1] = did
my_array[2] = Android
my_array[3] = Program
A part of program which I did looks like this:
StringTokenizer st = new StringTokenizer(result,"|");
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
while(st.hasMoreTokens())
{
String n = (String)st.nextToken();
services1[i] = n;
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
}
Can any one please suggest some ideas..
Why not use String.split() ?
You can simply do
String[] my_array = myStr.split("\\s+");
Since '|' is a special character in regular expression, we need to escape it.
for(String token : result.split("\\|"))
{
Toast.makeText(appointment.this, token, Toast.LENGTH_SHORT).show();
}
You can use String.split or Android's TextUtils.split if you need to return [] when the string to split is empty.
From the StringTokenizer API docs:
StringTokenizer is a legacy class that
is retained for compatibility reasons
although its use is discouraged in new
code. It is recommended that anyone
seeking this functionality use the
split method of String or the
java.util.regex package instead.
Since String is a final class, it is by default immutable, which means you cannot make changes to your strings. If you try, a new object will be created, not the same object modified. Therefore if you know in advance that you are going to need to manipulate a String, it is wise to start with a StringBuilder class. There is also StringBuffer for handling threads. Within StringBuilder there are methods like substring():
substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this character sequence.
or getChars():
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
or delete():
delete(int start, int end)
Removes the characters in a substring of this sequence.
Then if you really need it to be a String in the end, use the String constructor(s)
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
or
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
Although to understand when to use String methods and when to use StringBuilder, this link or this might help. (StringBuilder comes in handy with saving on memory).