I'm using the below code to find a resource by id;
setContentView(R.layout.golders);
for (int i=1; i<hm.size()+1;i++)
{
int id = getStringIdentifier("Bus"+i);
view = (TextView)findViewById(id);
view.setText(hm.get(i).toString());
}
My getStringIdentifier() is working but when I try to set the text I'm getting a NullPointerException.
I've used the setContentView to focus on the golders.xml file which has the ids that I want to update.
I've tried Cleaning the project but that hasn't done anything either, any ideas?! Thanks!
EDIT:
public int getStringIdentifier(String aString)
{
String packageName = "com.example.bustimetable.Robbos";
int resId = getResources().getIdentifier(aString, "string", packageName);
return resId;
}
Your getStringIdentifier(String) method returns a string ID (something from R.string). You need a new method, something like getIdentifier(String), that will return soemthing from R.id. I can't see the XML, so I don't know what your TextView's ID is, but... you'll want to verify that the ID is, in fact, Bus_ where the _ is some number.
public int getIdentifier(String aString)
{
String packageName = "com.example.bustimetable.Robbos";
int resId = getResources().getIdentifier(aString, "id", packageName); // Get from R.id, not R.string
return resId;
}
The problem is that getStringIdentifier() is returning an id for a string resource. Apparently the id which is returned is not a valid id for a view resource. Even if was, I don't know how you can guarantee that you will get the view that you want. You need to either add another method to return id's for view resources, or modify the one you have so that it will return id's for either string or view resources
Related
In my android application I have categories that stored in categories table of database. And I want to assign icons for each category. Category table looks like:
The problem is that I am not able to use drawable constants that defined in R file because they are not static and will be changed from build to build.
Is it correct to create public.xml file and define all drawable constants inside the file?
I am afraid that I can override some android constants using this approach.
Why don't you simply use the drawable names?
You can get the resource id at run time, for the given resource name and type.
Add this method to your code:
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
And use it like this:
int myID =
getResourceID("your_resource_name", "drawable", getApplicationContext());
Note: no path nor extension, in case of images.
I think you need this:
int imageResource = context.getResources().getIdentifier(imageName,
"drawable", context.getPackageName());
and if you want to set the image to an imageView:
// set the image
if (imageResource != 0)
yourImageView.setImageResource(imageResource);
I'm trying to pull out all the TextViews that have been assigned id's in an Activity in order to populate them with dynamic values. In order to do so, I'm using an XMLResourceParser to go through the tags and get the id's. Here's the code:
public int[] getElementIds(int layoutId, String viewType)
throws XmlPullParserException, IOException{
XmlResourceParser parser = activity.getResources().getLayout(layoutId);
LinkedList<Integer> idList = new LinkedList<Integer>();
while(parser.getEventType()!=XmlResourceParser.END_DOCUMENT){
parser.next();
if(parser.getEventType()==XmlResourceParser.START_TAG){
if(parser.getName().equals(viewType)){
idList.add(parser.getIdAttributeResourceValue(0)); //here's the problem
}
}
}
// returns an int[] from values collected
}
The line with the comment just gives me back zeroes, the default value I specified. The following code, however, worked, the attribute index worked out through trial and error:
idList.add(parser.getAttributeResourceValue(0, 1)); // the zero here is 'id' attribute index
Any ideas?
After additional research, it seems that I've found a bug in the API. The code that was available online looks like this:
public int getIdAttributeResourceValue(int defaultValue) {
return getAttributeResourceValue(null, "id", defaultValue);
}
public int getAttributeResourceValue(String namespace, String attribute, int defaultValue) {
int idx = nativeGetAttributeIndex(mParseState, namespace, attribute);
if (idx >= 0) {
return getAttributeResourceValue(idx, defaultValue);
}
return defaultValue;
}
public int getAttributeResourceValue(int idx, int defaultValue) {
int t = nativeGetAttributeDataType(mParseState, idx);
// Note: don't attempt to convert any other types, because
// we want to count on appt doing the conversion for us.
if (t == TypedValue.TYPE_REFERENCE) {
return nativeGetAttributeData(mParseState, idx);
}
return defaultValue;
}
Wherein the last function is the one actually doing the work. There is no documentation for this class (XMLBlock), and I have no access to the native functions, which are actually written in C. What I do know is that the offending function here is the second one, with namespace and attribute name being the parameters. For attribute name 'style' it works fine, but for 'id' (which is both the name provided by the API in another place, and the value returned by a different function that returns attribute name, provided a given index), it doesn't come up with anything, and consistently spits out the default value. Furthermore, I can access those same id values by using the function whose parameters are attribute index rather than name (the last function copied above). Conclusion: something is messed up with the way the 'native' code processes the name 'id'. I'm sending a bug report to the open source project, and I'll post any response I get.
As a workaround I've implemented this function in my own code:
private int getIdAttributeResourceValue(XmlResourceParser parser) {
final int DEFAULT_RETURN_VALUE = 0;
for (int i = 0; i < parser.getAttributeCount(); i++) {
String attrName = parser.getAttributeName(i);
if ("id".equalsIgnoreCase(attrName)) {
return parser.getAttributeResourceValue(i, DEFAULT_RETURN_VALUE);
}
}
return DEFAULT_RETURN_VALUE;
}
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 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]);
This question already has answers here:
Android, getting resource ID from string?
(14 answers)
Closed 2 years ago.
How do I get the resource id of an image if I know its name (in Android)?
With something like this:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
You can also try this:
try {
Class res = R.drawable.class;
Field field = res.getField("drawableName");
int drawableId = field.getInt(null);
}
catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
}
I have copied this source codes from below URL. Based on tests done in this page, it is 5 times faster than getIdentifier(). I also found it more handy and easy to use. Hope it helps you as well.
Link: Dynamically Retrieving Resources in Android
Example for a public system resource:
// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");
Another way is to refer the documentation for android.R.drawable class.
You can use this function to get a Resource ID:
public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException {
try {
return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
} catch (Exception e) {
throw new RuntimeException("Error getting Resource ID.", e)
}
}
So if you want to get a Drawable Resource ID, you can call the method like this:
getResourseId(MyActivity.this, "myIcon", "drawable", getPackageName());
(or from a fragment):
getResourseId(getActivity(), "myIcon", "drawable", getActivity().getPackageName());
For a String Resource ID you can call it like this:
getResourseId(getActivity(), "myAppName", "string", getActivity().getPackageName());
etc...
Careful: It throws a RuntimeException if it fails to find the Resource ID. Be sure to recover properly in production.
Read this
One other scenario which I encountered.
String imageName ="Hello"
and then when it is passed into
getIdentifier function as first argument, it will pass the name with string null termination and will always return zero.
Pass this
imageName.substring(0, imageName.length()-1)