How to concatenate strings and integer into a variable - android

It is a real silly questions but I can't get it to work. I've used the search option, but couldn't not find my answer for android.
What I would like to do it the following:
In res/strings.xml i've got several strings
<string name="good0">blablabla</string>
<string name="good1">balablabla2</string>
etc
I want to show those strings randomly in a those when something happens:
Toast.makeText(this,R.string.good+(Math.random()*10), Toast.LENGTH_LONG).show();
But this doesn't work.
Thanks a lot for your help!

Use a String Array.
In strings.xml:
<resources>
<string-array name="messages">
<item>blablabla</item>
<item>blablabla</item>
</string-array>
</resources>
Then, in code you will have something like:
String[] messages = getResources().getStringArray(R.array.messages);
Random r = new Random();
String message = messages[r.nextInt(messages.length)];
Toast.makeText(this, message, Toast.LENGTH_LONG).show();

R.string.good is an int because it refers to a Resource. This int IDENTIFIES a string in an XML file. Android provides a getString() for its resource identifiers.
Android Docs on String Resources
You'll have to get the String out of the resource file this way, then concatenate as normal.

You can't do that.
You will have to use a switch block.
String myString;
switch(Math.random() * 10) {
case 0:
myString = getString(R.string.good1);
break;
}
Toast.makeText(this, myString, Toast.LENGTH_LONG).show();

If you have multiple string values or integer values and you to store it in a single string then String Builder is the best for this
type of operation, For Example you have a string array and you want to
store in a single string and then display this string then use this
method. it will work hundred percent and it is too much suitable for
this type of problems.**
String my_str=null;
StringBuilder bldr=new StringBuilder();
for(int j=0;j<5;j++)
bldr.append(phonearray[j]).append(",");
my_str=bldr.toString();
here in this case i am assigning phone array to a single string and
then i will display it etc...

Related

How can i get few characters from String?

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);

Randomly select a string from strings.xml in Android

I need to randomly select a string defined within strings.xml file in android.
For example my strings.xml is :
<resources>
<string name="str1">Content comes here1</string>
<string name="str2">Content comes here2</string>
<string name="str3">Content comes here3</string>
</resources>
Can I randomly select one of these strings in my Activity?
Create an array contains all of your resource names you want to select:
String[] strs = new String[] {"str1", "str2", "str3"};
Get a random index:
int randomIndex = new Random().nextInt(3);
Get your random string from resource:
int resId = getResources().getIdentifier(strs[randomIndex ], "string", your_package_name);
String randomString = getString(resId);
The best way is you declare you Strings as an Array, then get it like this:
String[] arrayOfStrings = context.getResources().getStringArray(R.array.your_string_array);
String randomString = arrayOfStrings[new Random().nextInt(arrayOfStrings.length)];
Then you can use it as you like.
You would probable rather make it an array of strings (and then that is easier to select at random one of the array). Else, you can put the ids of your strings in an array and randomly select one of the items in the array.

Can you call a string resource with a string?

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]);

Compare and return String values to a string-array in Xml Android

Good day, i will try to explain my problem as best as i can. i have in one of my class, getters and setters for a string object. Now in my getString() method, i am trying to compare the string to a string-array of items in my String.xml to see if any of the elements in the string-array file matches the given string and return that matched item element in the string array.
I have something like this so far:
for setPlace():
public void setPlace(String place) {
this.place = place;
}
for getPlace():
public String getPlace() {
//am stuck here and not sure how to compare this and return the correct item
if(place.equals(context.getResources().getStringArray(R.array.myPlacesArray))){
//return context.getResources().getString();
}
my Strings.xml file:
<string-array name="myPlacesArray">
<item>#string/myplace1</item>
<item>#string/myPlace2</item>
<item>#string/myPlace3</item>
</string-array>
<string name="myplace1">home</string>
<string name="myplace2">office</string>
<string name="myplace3">gym</string>
the reason i have to do this, is because it has different locales(languages) values and it would be a lot easier than writing a huge list of if/else or switch statements for different String elements and languages. Please any ideas is highly appreciated. Thank you
Check this Code for getting value from String.xml and compare :
String[] categoriesAndDescriptions =getResources().getStringArray(R.array.myPlacesArray);
for(String cad : categoriesAndDescriptions) {
String categoryAndDesc = cad;
Log.v("CategoryName", categoryAndDesc);
if(place.equalsIgnoreCase(categoryAndDesc)){
//Do your Stuffs here
}
}
You should just loop over the returned array, doing a place.equals on each item in that array, and return the match when they match.
If they're sorted (they're not in this case) you could use Arrays.binarySearch. You could also use Arrays.asList and call contains(place) on the resulting list, which is essentially the same as looping manually.
You'd need to decide what to return if there's no match (if that's even possible).

Android String Array Manipulation

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).

Categories

Resources