Vilrouge
Vilrouge

Reputation: 67

getting a stringArray resource with a string variable

I am trying to get a stringArray resource with this code:

String continent = "europe";  
getResources().getStringArray(R.array.continent);

If I type R.array.europe, its ok, but I want this to be dynamic, so I'm looking for a way to use my string variable here..

This is probably a simple java problem, but I'm quite a noob both in java and android programming, and I didn't find the answer..

Thanks in advance;

edit: so here is my complete onCreate Method, did I do something wrong?

protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
       String continent = (String) getIntent().getExtras().getString("continent");

       int holderint = getResources().getIdentifier(continent, "Array",
               this.getPackageName());

       String[] items = getResources().getStringArray(holderint);


        setListAdapter(new ArrayAdapter<String>(this, 
                android.R.layout.simple_list_item_1, 
                items));

    }

I'm not sure about the defPackage part though...

Upvotes: 0

Views: 2383

Answers (5)

Saurabh Padwekar
Saurabh Padwekar

Reputation: 4074

You can get the array resource id using this :

Sting name = "resource_array_name";
int resourceId= getResources().getIdentifier(name, "array",this.getPackageName());
String[] items = getResources().getStringArray(resourceId);

Upvotes: 0

Hamlet Kraskian
Hamlet Kraskian

Reputation: 801

I had the same problem. Using

getResources().getIdentifier(String name, String defType, String defPackage);

with

name : should be the resource name inside the file. ( Avoid adding R.array. in the begining of your resource name, because there is no resource with name R.array.yourname ) deftype: Should be "array". defPackage: this.getPackageName()

The problem has been solved

Upvotes: 0

alice_silver_man
alice_silver_man

Reputation: 412

Here is an alternate approach that I find easy to use:

int resourceId = R.array.class.getField(yourStringVariable).getInt(null); String[] yourStringArray = getResources().getStringArray(resourceId);

Note that yourStringVariable is in the form "europe", not "R.array.europe".

Upvotes: 0

Richard Lewin
Richard Lewin

Reputation: 1870

With the name of the resource created dynamically in code, you could look at using

getResources().getIdentifier(String name, String defType, String defPackage);

This will return an id for a specified resource.

Upvotes: 2

bschultz
bschultz

Reputation: 4254

You could create a String variable containing "R.array." and append it with your continent object.

Upvotes: 1

Related Questions