Issue
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?
Solution
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.
Answered By - olivierg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.