0

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".

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

This probably looks like what you wanted:

http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.