Reputation: 75
Background: For my Android app, I am using a ListView and the list items trigger sounds, that are stored as .ogg files in the /res/raw/ directory. I was able to automatically set the text labels and length of the listview through string-arrays stored in strings.xml, now I need an additional array of ResIDs that I would like to store there as well for convenient expansion of the listview in the future.
Working code: For the string arrays, I use this code: Java Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
titles = getResources().getStringArray(R.array.listoftitles);
XML (strings.xml):
<string-array name="listoftitles">
<item>Title1</item>
<item>Title2</item>
</string-array>
Problematic code: Java Fragment:
filenames = new int[]{R.raw.both1, R.raw.both2, R.raw.both3, R.raw.both4, R.raw.both5
, R.raw.both6, R.raw.both7, R.raw.both8, R.raw.both9, R.raw.both10, R.raw.both11
, R.raw.both12, R.raw.both13, R.raw.both14, R.raw.both15, R.raw.both16, R.raw.both17
, R.raw.both18, R.raw.both19};
Target:
private void populatemylist() {
for (int i = 0; i < titles.length; i++) {
itemsdb.add(new Item(titles[i], descriptions[i], filenames[i]));
}
}
The convenience of the method populatemylist() is crucial and while titles[] and descriptions[] are easily fetched from the xml arrays, it does not work for the filenames, which I need as a ResID / int value. I tried using an integer-array, as well as a generic array with a TypedArray Java backend, but this seems to be targeted towards drawables and I just can't get it to fetch anything from the /res/raw/ folder. I would like to have a simple array solution, that goes in the strings.xml in the fashion of
<item>R.raw.both1</item>
and a simple java backend, that gets me an int array of those filenames.
Upvotes: 1
Views: 2178
Reputation: 4567
You need to use TypedArray, let me know if you have any problems otherwise goodluck!
filenames.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="random_imgs">
<item>@raw/both1</item>
<item>@raw/both2</item>
<!-- ... -->
</string-array>
</resources>
private int getFileNameAtIndex(int index) {
TypedArray fileNames = getResources().obtainTypedArray(R.array.filenames);
// or set you ImageView's resource to the id
int id = fileNames.getResourceId(index, -1); //-1 is default if nothing is found (we don't care)
fileNames.recycle();
return id;
}
Upvotes: 1