Android Studio find xml data file by name - android

the problem is that I have various XML files with the data that I need for my app and I want to access to read them by the name of the XML file: "fileName.xml" so I can run the pull parser. Since the program only knows which file to load by its name which is given by a string I can't call them using r.id.fileName.xml.
I have tried things like:
int resID = getResources().getIdentifier("r.id.fileName", "id", getPackageName());
and then call it by this resID... but it doesn't seem to work (resID is always 0) :(
Any ideas?
Thank you!

The best solution from a performance standpoint is to have a mapping in your Java code between some string and the resource ID value:
private static HashMap<String, Integer> RESOURCES=new HashMap<>();
static {
RESOURCES.put("thingy", R.xml.thingy);
RESOURCES.put("thingy2", R.xml.thingy2);
// and so on
}
Then, you can just call RESOURCES.get() to retrieve the ID value, without having to use the reflection that goes on inside of getIdentifier().
If you really want to use getIdentifier(), then the syntax would be:
int resID = getResources().getIdentifier("fileName", "xml", getPackageName());
because:
the first parameter is the base name of the resource
the second parameter is the type of the resource, and the files in res/xml/ are not id resources

Related

Android: How to retrieve the int value of a specified id stated in String? [duplicate]

I have a short question:
How is it possible to convert a String, containing the Id of a Drawable, which is
String idString = "R.drawable.bubblegum";
to an Integer,
idInt
so that I can use that ID for the reference of an image (, which is used in a SimpleAdapter)
So, to make an example, I can't do that:
bubble.setImageDrawable(this.getResources().getDrawable(idString));
//not possible, cause idString is a String an not an Id/Int
So, I have the String that's containing the id, but unfortunately as a String.
Thanks!
Although this question is rather old already, the thing you're missing is that "id" and "drawable" are different resource types. So instead of
getResources().getIdentifier(stringId, "id", "my.Package");
it's
getResources().getIdentifier(stringId, "drawable", "my.Package");
You can also get package name with the activity context like activityContext.getPackageName()
/**
* Returns Identifier of String into it's ID as defined in R.java file.
* #param pContext
* #param pString defnied in Strings.xml resource name e.g: action_item_help
* #return
*/
public static int getStringIdentifier(Context pContext, String pString){
return pContext.getResources().getIdentifier(pString, "string", pContext.getPackageName());
}
Call getIdentifier() on the Resources object you get via getResources(), as seen in these StackOverflow questions:
Is possible in Android to findView by String id?
Android findViewbyId with a variant string
How to access R.string.xxx resources from a method by passing string 'xxx' as parameter to that method?
Dynamically build a resource Identifier
How to access the values from strings.xml dynamically?
Drawable resource using a variable
among others.
You could try the following
int id = getResources().getIdentifier("arr_name"+positionSelected,
"array", rootview.getContext().getPackageName());
I use in spinner dropdown, get array string follow parent spinner
may help you!
int idInt = R.drawable.bubblegum;
Unless there's something I'm missing here.
if your idString is constant, i.e. it's doesn't change during runtime, follow DeeV's answer.
If it changes, you can take a look at getIdentifier method.
At least, I couldn't get a solution for this problem. It seems that there's no way to convert a String "R.id.mytext" into an integer like R.id.mytext that can be used in findViewById(R.id.myText).

how I can get array based on another array position ? in android

I want to get an array based on another array click position like :
String[] nissanArray = getResources().getStringArray(R.array.nissan);
String name = nissanArray[pos];
int nameInt = Integer.parseInt("R.array." + name);
targetArray = getResources().getStringArray(nameInt);
and I got an error when using this : I believe the error starts from Line int ....
You can use the getIdentifier method of class android.content.res.Resources. See the documentation for the details.
It allows you to convert a resource name to the integer resource id.
do you know what you are trying to do ?? first understand your code
getStringArray(R.array.nissan);
in that integer parameter we should pass
that you are trying to pass integer using convert string into int is totally wrong
it required integer which mentioned in R.java file and it cant retrieved it by your syntax
when you write (R.Array.nissan)
then it linked R.java file and return integer for that from file

Getting a string from strings.xml using the string form of the ID

In Android, to access a string from the strings.xml file, we use R.string.string_id. Would it be possible to have a method such that we'll use the string form of string_id? I mean can we for example have a method GetString("string_id") to retrieve R.string.string_id?
//Replace this with appropriate context
String name = "name_of_your_string_in_strings_xml_file_goes_here";
int resId = this.getResources().getIdentifier(name, "string", this.getPackageName());
String string = this.getResources().getString(resId);
It is possible. You have to understand the fact that any data that is pinned to xml files in android are considered as resource to the app. And android resource can be accessed only by means of unique id we provide to them. These ids that are generated are of type int and hence we need to pass a int parameter to get a reference to these resource at run time.
But it is not that only the default way to access them is by using their res value but instead if you could know the name of the string key you could find the id from there and then use the int id to do this.

Convert String containing an ID into an Integer-ID

I have a short question:
How is it possible to convert a String, containing the Id of a Drawable, which is
String idString = "R.drawable.bubblegum";
to an Integer,
idInt
so that I can use that ID for the reference of an image (, which is used in a SimpleAdapter)
So, to make an example, I can't do that:
bubble.setImageDrawable(this.getResources().getDrawable(idString));
//not possible, cause idString is a String an not an Id/Int
So, I have the String that's containing the id, but unfortunately as a String.
Thanks!
Although this question is rather old already, the thing you're missing is that "id" and "drawable" are different resource types. So instead of
getResources().getIdentifier(stringId, "id", "my.Package");
it's
getResources().getIdentifier(stringId, "drawable", "my.Package");
You can also get package name with the activity context like activityContext.getPackageName()
/**
* Returns Identifier of String into it's ID as defined in R.java file.
* #param pContext
* #param pString defnied in Strings.xml resource name e.g: action_item_help
* #return
*/
public static int getStringIdentifier(Context pContext, String pString){
return pContext.getResources().getIdentifier(pString, "string", pContext.getPackageName());
}
Call getIdentifier() on the Resources object you get via getResources(), as seen in these StackOverflow questions:
Is possible in Android to findView by String id?
Android findViewbyId with a variant string
How to access R.string.xxx resources from a method by passing string 'xxx' as parameter to that method?
Dynamically build a resource Identifier
How to access the values from strings.xml dynamically?
Drawable resource using a variable
among others.
You could try the following
int id = getResources().getIdentifier("arr_name"+positionSelected,
"array", rootview.getContext().getPackageName());
I use in spinner dropdown, get array string follow parent spinner
may help you!
int idInt = R.drawable.bubblegum;
Unless there's something I'm missing here.
if your idString is constant, i.e. it's doesn't change during runtime, follow DeeV's answer.
If it changes, you can take a look at getIdentifier method.
At least, I couldn't get a solution for this problem. It seems that there's no way to convert a String "R.id.mytext" into an integer like R.id.mytext that can be used in findViewById(R.id.myText).

Load resources with variables?

I am loading XML file resource like this,
getResources().getXml(R.xml.fiel1);
Now, the scenario is that depending on factors there may be many xml files to choose from. How do I do that?
In this case the filename is similar in the fact that all starts with file only ends with different numbers like
file1, file2,file3 etc., So I can just form a String variable with the file name and add a suffix as per requirement to form a filename like file1 (file+1).
Problem is I keep getting various errors (NullPointerEx, ResourceId Not found etc) in whatever way I try to pass the filename variable to the method.
What is the correct way of accomplishing this?
You could use getIdentifier() but the docs mention:
use of this function is discouraged.
It is much more efficient to retrieve
resources by identifier than by name.
So it's better to use an array which references the xml files. You can declare it as an integer array resource. Eg, in res/values/arrays.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer-array name="xml_files">
<item>#xml/file1</item>
<item>#xml/file2</item>
etc...
</integer-array>
</resources>
And then in Java:
private XmlResourceParser getXmlByIndex(int index) {
Resources res = getResources();
return res.getXml(res.getIntArray(R.array.xml_files)[index - 1]);
}
Of course, you'll need to update the array whenever you add a new xml file.
You can use the getIdentifier method of Resources to find the id.
Resources res = getResources();
for(/* loop */) {
int id = res.getIdentifier("file" + i, "xml", "my.package.name");
res.getXml(id);
}
An alternative to the getIdentifier suggestions, assuming the number of resources is fixed at compile time, would be to create a static mapping between an identifier and the resource.
So for example you could use the suffixed numerical ID:
class Whatever {
static final int[] resources = new int[] {
R.xml.file1, R.xml.file2, R.xml.file3
}
}
This would allow you retrieve the resource with a simple index operation.
getResources().getXml(resources[i]);
Alternatively, if you needed a more descriptive mapping you can use any one of java's Map-based classes.
class Whatever {
static final Map<String, Integer> resources = new HashMap<String, Integer>();
static {
resources.put("file1", R.xml.file1);
resources.put("file2", R.xml.file2);
resources.put("file3", R.xml.file3);
resources.put("something_else", R.xml.something_else);
}
}
With this you would then get(String) the value by its name.

Categories

Resources