0

I'm looking for a way to insert the variable <array_name> inside the argument <R.array._____>

E.g.

int arrayName = booksArray;

ArrayAdapter<CharSequence> arrAdapter;

arrAdapter = ArrayAdapter.createFromResource(context: this, R.array.<booksArray>, android.R.layout.simple_spinner_item);

Thanks,

  • 1
    Hi Joseph! If I get it correctly what you'd like to do is to dynamically change the value of `arrRep` variable before passing it in to `createFromResource` method, is that right? If that's the case you can do it, you just need to declare the `arrRep` variable as an `Int` instead of a `String`, as that's the type `createFromResource` is expecting. So your declaration would be `int arrRep = R.array.array_name;` :) – Marino Aug 15 '20 at 17:21
  • Thanks Marino, I've made a slight change on the code to show exactly the issue I'm trying to resolve. Appreciate your help! – Joseph Namulauulu Aug 15 '20 at 18:19
  • Does this answer your question? [How to get a resource id with a known resource name?](https://stackoverflow.com/questions/3476430/how-to-get-a-resource-id-with-a-known-resource-name) – Ryan M Aug 16 '20 at 07:33

1 Answers1

0

You can get the ID of a resource like this:

String arrRep = "array_name";
int arrId = getResources().getIdentifier(arrRep, "array", getPackageName());

then you can pass it to ArrayAdapter:

arrAdapter = ArrayAdapter.createFromResource(context: this, arrId, android.R.layout.simple_spinner_item);
Tal Mantelmakher
  • 994
  • 1
  • 7
  • 23
  • Hi Tal, thanks for your help. I will try and explore the options you've mentioned in your comment. I'm new in Android Studio and I'm trying to use my Java skills in for the app I'm working on right now. I appreciate your comment and idea! – Joseph Namulauulu Aug 15 '20 at 18:23