0

I have a few drawables:

R.drawable.pres01
R.drawable.pres02
R.drawable.pres03

I want to use SharedPreference to display the proper drawable:

private SharedPreferences prefs;
private SharedPreferences.Editor editor;
String someId;
ImageView ivPresident;
int inAdd;

prefs = this.getSharedPreferences("pNum", Context.MODE_PRIVATE);

someId = prefs.getString("presNum", "");
inAdd = Integer.parseInt(someId);

ivPresident = (ImageView) findViewById(R.id.imgViewPresident);

I converted the String to Integer, now how do I set the image source of ivPresident to the number based on the saved string.

So for example:

if someId is 01 the drawable for ivPresident is R.drawable.pres01

if someId is 02 the drawable for ivPresident is R.drawable.pres02

if someId is 03 the drawable for ivPresident is R.drawable.pres03

I tried the following but did not work:

ivPresident.setBackground(R.drawable.pres + inAdd);

How do I fix the code to achieve it?

Si8
  • 9,141
  • 22
  • 109
  • 221
  • 1
    seems to me you are creating unnecessary work for yourself when all you have to do to access it is use `getResources()` – tyczj Sep 16 '13 at 17:50
  • I am not sending `R.drawable.pres01` I am only sending `01`. Should I send the entire string? Will it make it easy? – Si8 Sep 16 '13 at 17:59
  • what is wrong with just using it the normal way ie. `getResources().getDrawable(R.drawable.pres01);` – tyczj Sep 16 '13 at 18:01

1 Answers1

1

What you want is:

Resources.getIdentifier(String name...)

See here

Build the string the way you are trying now.

EDIT:

String someId = prefs.getString("presNum", "");
int id = getResources().getIdentifier("pres0" + someId, "drawable", getPackageName())
ivPresident.setBackgroundResource(id);
Johnny Z
  • 14,329
  • 4
  • 28
  • 35
  • Would you be kind enough to give me an example with what I provided? – Si8 Sep 16 '13 at 17:54
  • I am not sending R.drawable.pres01 I am only sending 01. Should I send the entire string? Will it make it easy? – Si8 Sep 16 '13 at 18:00
  • 1
    setBackground() does not or no longer takes an int. Use setBackgroundResource(int) – Steve G. Jan 13 '15 at 17:55