-2

this is a question about java on android - eclipse I have a String r for the record, I defind him like that:

String r="pic"+c1;

I want to take the value of it, which is "pic6" and use it as a variable name.

how do I do it?

Cœur
  • 37,241
  • 25
  • 195
  • 267

4 Answers4

5

If you want to pick an image with name "pic6.png" from the drawable folder of the Android application, you can try the following code.

String r = "pic" + c1;

int resId = getResources().getIdentifier(r, "drawable", getPackageName());
if (resId != 0) {
    imageView.setImageResource(resId);
} else {
    // This is used in case no image resource is found
    imageView.setImageResource(R.drawable.unknown);
}

Please see: If you use the else part, then you need to add "unknown.png" image to the drawable folder of the Android project.

Hope this helps.

jagmohan
  • 2,052
  • 2
  • 26
  • 41
2

You can't do it directly but you could use a HashMap to emulate what you seek.

Example:

String r="pic"+c1;
HashMap<String,Integer> extendedVars=new HashMap<>();
extendedVars.put(r,10);
Lan
  • 1,206
  • 1
  • 11
  • 26
  • 1
    sorry, I dont know what HashMap is... I have this code: `String r="pic"+c1; pic6.setImageDrawable(getResources().getDrawable( R.drawable.orange));` I want to put r instead of pic6. – Alon Lousky Nov 01 '13 at 09:44
  • 1
    @AlonLousky A map maps keys to values, so you can use it to emulate dynamic variable declaration (say you later write an interpreter). You could say HashMap varMap=new HashMap<>(); varMap.put("pic6", new ...); then later call varMap.get("pic"+c1).setImageDrawable(.....) – Lan Nov 01 '13 at 10:04
  • 1
    @AlonLousky Considering this is an Android question (didn't notice that in my original answer), you may want to look at http://stackoverflow.com/questions/10137692/how-to-get-resource-name-from-resource-id & http://stackoverflow.com/questions/3476430/how-to-get-a-resource-id-with-a-known-ressource-name/3476470#3476470 – Lan Nov 01 '13 at 10:06
  • great, it very helped me. thanks guys! – Alon Lousky Nov 01 '13 at 10:53
2

Like Eng. Fouad said. Dynamic variables are not supported in Java.
Same question can be found Here

Community
  • 1
  • 1
Fabian
  • 356
  • 1
  • 5
  • 15
1

In java, variable names must be known in compile time. There is no way to do what you are trying to do.

LeeNeverGup
  • 1,096
  • 8
  • 23