usealbarazer
usealbarazer

Reputation: 707

Getting a field value as a string in java (Android)

See code below...

public static final int s1 = R.raw.s_1slow1;
public static final int s2 = R.raw.s_2fast6;
public static final int s3 = R.raw.s_3slow4;

String trackName = "s" + selectedTrack; //selectedTrack is an integer(1-3) 
mPlayer = MediaPlayer.create(getApplicationContext(), 
this.getClass().getField(trackName).getName()); //failed attempt

Is there a way to get the resource ID, based on a string?
For example I would need the value of "R.raw.s_1slow1".

Upvotes: 0

Views: 978

Answers (2)

Marius Burz
Marius Burz

Reputation: 4655

Why not use a Map?

public static final Map<Integer, Integer> m;
static {
    m = new HashMap<Integer, Integer>(3);
    m.put(1, R.raw.s_1slow1);
    m.put(2, R.raw.s_2fast6);
    m.put(3, R.raw.s_3slow4);
}
m.get(selectedTrack);

Using reflection like that is a very bad idea.

If you want to do it with reflection, this is how you could, but I strongly advice against doing it this way:

Field field = this.getClass().getField("s1");
int s1val = field.getInt(this);
System.out.println(s1val);

Upvotes: 1

Related Questions