I have many string arrays in my resource files, and I want to access them programmatically depending on user input.
int c = Getter.getCurrentNumber();
String[] info = getResources().getStringArray(R.array.n_<c>);
So if c==12, info should be the string-array with name "n_12".
Is there a way to do this, and avoiding to do a switch statement with hundreds of cases?
Thanks
You can get the resource id like so
int c = Getter.getCurrentNumber();
String resource = "n_" + c;
int id = getResources().getIdentifier(resource, "array", "com.your.project");
Then just use that id
String[] info = getResources().getStringArray(id);
Have a look here for another example on getResources().getIdentifier().
If you want to get a resource by name (programmatically) and you are not sure how to address the resource by name (but you do know how to access it by R.), you can do this:
First print the exact resource name, like this:
Log.d("", context.getResources().getResourceName(R.id.whichYouAlreadyKnow) );
(Note: R.id.whichYouAlreadyKnow can be R.string.* R.drawable.* etc...)
Now you know the exact Resource address name
Take the printed name and use it as is, like this:
int id = getResources().getIdentifier(resource_name_that_printed_above, null, null);
Cheers
Related
I'm looking for a solution for my problem with automatic connection ImageView with a proper JPG from resources.
I have a simple array with names of gods like:
final String[] godslist = {"Achilles", "Agni", "Ah Muzen Cab", "Ah Puch", "Amaterasu", "Anhur", "Anubis", "Ao Kuang", "Aphrodite", "Apollo", "Arachne", "Ares", "Artemis", "Artio"}
final ImageView godImage = findViewById(R.id.godImage);
final TextView godName = findViewById(R.id.nameOfGod);
int randomGod = (int) (Math.random() * 14);
godName.setText(godslist[randomGod]);
And for now, it's working fine. In the TextView I get the random name of a god from the array.
The problem is with connecting chosen god with his image. I thought about a loop that will search resources by name of chosen god e.g. "Achilles". In resources, I have a file named "achilles.jpg" e.t.c., so it should be godName.setImageResource(R.drawable.achilles);. Not every god's name is consisting of one word only - like "Ah Muzen Cab" and drawable can't be named with spaces (but this is not a big problem for now). For some reasons drawable can't also be named starting with an uppercase character, so I probably need to do something like this:
godName.setText(godName.getText().toString().toLowerCase());
And then I should use some loop to find the name in resources. Below code should be easiest, if it would work like that, but...
godImage.setImageResource(R.drawable.(godName.setText(godName.getText().toString().toLowerCase())));
The same problem is with sounds from resources (depending on which god is randomly chosen), but it will be easier when I figure out how set images. Thank you for any help.
You can incapsulate data in a separate class, and use its instances when randomly choosing an array index:
public class GodData {
public final String name;
public final String imageResId;
public final String soundResId;
public GodData(String name, String imageResId, String soundResId) {
this.name = name;
this.imageResId = imageResId;
this.soundResId = soundResId;
}
}
final GodData[] godslist = {new GodData("Achilles", R.drawable.achilles, R.raw.achilles_sound), ...}
GodData randomGod = godslist((int) (Math.random() * 14));
godName.setText(randomGod.name);
godImage.setImageResource(randomGod. imageResId);
Is this the right way to set text in TextView programmatically?
points_txt.setText(R.string.you_have + current_points + R.string.points);`
It shows me a ResourcesNotFoundException error for the string while I can see the string in the strings.xml file.
points_txt.setText(getResources().getString(R.string.you_have) + current_points + getResources().getString(R.string.points));
You get a ResourcesNotFoundException because you're adding int values (resource identifiers are mapped to int values at compile time) instead of concatenating Strings.
The sum of the various resource identifiers might even be another valid resource identifier, but that would only happen accidentally. Nevertheless, if you pass an int value into setText(), the runtime tries to find a string resource by that number. In your case, it failed and so your app crashed.
So you have to get the Strings first and concatenate them afterwards:
points_txt.setText(getString(R.string.you_have) + current_points + getString(R.string.points));
points_txt.setText(R.string.you_have + current_points + R.string.points);
This is showing "ResourcesNotFoundException" because "R.string.you_have" is an integer value an "current_point" variable also is an int type
setText() requires the String type...
to get string value of "R.string.you_have" you can use
getResources().getString(R.string.you_have);
points_txt.setText(getResources().getString(R.string.you_have) + current_points + getResources().getString(R.string.points));
To get a string from strings.xml do this:
String you_have = getResources().getString(R.string.you_have);
You are almost there but I feel might be behind a few steps but not sure about this since you haven't shared all of your code.
You need to wire in the TextView first between your Java class and XML
TextView tv1 = (TextView)findViewById(R.i.d.textView1)
Next is setting the String for the textview
tv1.setText(getResources().getString(R.string.you_have) + "current_points" + getResources().getString(R.string.points));
You are basically missing the " " marks which are compulsory when you are assigning hardcoded string.
You must firstly parse that resource to string:
String string = getString(R.string.yourString);
More about that here:
how to read value from string.xml in android?
So answer for your question will be literally as following:
String you_have = getString(R.string.you_have);
String points = getString(R.string.points);
points_txt.setText(you_have + current_points + points);
I am newcomer to programming and I am attempting to create an Android app using Android Studio. I've tried searching but my findings do not appear to be what I am looking for, because they seem to be overly complex. What I've written below is just an example.
I want to be able to return a string from string.xml when user types "whale". The string in this case is information about the whale.
This is my java file, animal is already a string entered from a form.
TextView textview = new TextView(this);
String animalType = "water_" + animal; // This become water_whale if user typed whale
String animalInfo = getString(R.string.animalType); // This doesn't work
textView.setText(animalInfo);
This is my string.xml
<string name="water_fish">Fish is a small bla...</string>
<string name="water_whale">A whale is an enourmous blabla...</string>
<string name="land_giraffe">Africa.</string>
I have probably tunneled on this particular way and I have probably miss something obvious or is there another way to do this?
R.string.anyIdentifer represents an integer value. You can't add your own identifier with it, just the way you can't call any non existent property on any class. If you want to access any resource dynamically with it's name then there is a different approach for that.
Use this
TextView textview = new TextView(this);
String animalType = "water_" + animal;
int animalTypeId = getResources().getIdentifier(animalType, "string", getActivity().getPackageName())
String animalInfo = getResources().getString(animalTypeId);
textView.setText(animalInfo);
String string=getResources().getString(R.string.water_whale);
you can't use getString() method directly.
I am looping through a list of checkboxes upon click of a button. What I am looking to do is grab the name of the checkbox at runtime to strip out an integer value specified within the name. I am not looking to get the value nor the id. So in the strings.xml file, <string name="checkList1">Pain assessment.</string>, I am trying to get checkList1 at run time. I can get the text without a problem. Currently I am looping through the view elements with the code below:
RelativeLayout root = (RelativeLayout)findViewById(R.id.Root);
for (int i = 0; i < root.getChildCount(); i++)
{
View v1 = root.getChildAt(i);
Class c = v1.getClass();
if (c == CheckBox.class)
{
CheckBox thisBox = (CheckBox)v1;
if (thisBox.isChecked())
{
String text = (String)thisBox.ge;
DoDailyCheckListUpdate(thisBox.isChecked(),checkBoxCount);
countItemsFinished++;
}
checkBoxCount++;
}
}
What I am looking for is to somehow get the name of Checkbox thisBox. So when it loops through and hits the Pain Assessment checkbox, I want to be able to pull out checkList1. Without going as far as ripping through the strings.xml file based on the text I find to get the name, I was hoping maybe there was a simpler solution that I maybe overlooking.
Thank You in advance.
CheckBox extends from TextView so to retrieve a text from it is quite simple :
String text = thisBox.getText().toString();
http://developer.android.com/reference/android/widget/CheckBox.html
If you want to retrieve the key name of the string. I suggest you put it into the tag of the object :
thisBox.setTag(getResources().getResourceEntryName(R.string. checkList1);
Retrieve it like that :
String text = (String)thisBox.getTag();
that should do the trick.
I have many string arrays in my resource files, and I want to access them programmatically depending on user input.
int c = Getter.getCurrentNumber();
String[] info = getResources().getStringArray(R.array.n_<c>);
So if c==12, info should be the string-array with name "n_12".
Is there a way to do this, and avoiding to do a switch statement with hundreds of cases?
Thanks
You can get the resource id like so
int c = Getter.getCurrentNumber();
String resource = "n_" + c;
int id = getResources().getIdentifier(resource, "array", "com.your.project");
Then just use that id
String[] info = getResources().getStringArray(id);
Have a look here for another example on getResources().getIdentifier().
If you want to get a resource by name (programmatically) and you are not sure how to address the resource by name (but you do know how to access it by R.), you can do this:
First print the exact resource name, like this:
Log.d("", context.getResources().getResourceName(R.id.whichYouAlreadyKnow) );
(Note: R.id.whichYouAlreadyKnow can be R.string.* R.drawable.* etc...)
Now you know the exact Resource address name
Take the printed name and use it as is, like this:
int id = getResources().getIdentifier(resource_name_that_printed_above, null, null);
Cheers