0

How to set image from PNG based on dynamic drawable name?

I use following code byt getting the error.

I have PNGs:

R.drawable.model_1.png
R.drawable.model_2.png
... and etc

Code

try
{
    String imageName = "model_" + uv.categoryID;
    int id = context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
    imageView.setImageResource(id);
}
catch(Exception ex)
{
    Log.e(TAG, ex);
}

Error

Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference

KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
NoWar
  • 36,338
  • 80
  • 323
  • 498
  • 3
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – AskNilesh Dec 21 '17 at 06:35

3 Answers3

2

It seems that you forgot to bind the ImageView.

imageView = (ImageView) findViewById(R.id.image_view_id);
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Tenten Ponce
  • 2,436
  • 1
  • 13
  • 40
  • 2
    You should use `context.findViewById(R.id.image_view_id);` .And it was more better.Because he use `context.getResources().getIdentifier` . – KeLiuyue Dec 21 '17 at 06:32
  • I assume that he's doing this on an activity. Well that's another optional answer. Thanks for suggesting. – Tenten Ponce Dec 21 '17 at 06:34
2

Try this:

    try
    {
        ImageView imageView = (ImageView)findViewById(R.id.imageView);
        int categoryID = 0;
        String imageName = "model_" + categoryID;
        int id = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());
        imageView.setImageResource(id);
    }
    catch(Exception ex)
    {
        Log.e("NIKHIL", ex.toString());
    }
Nikhil Lotke
  • 605
  • 7
  • 15
1

Try this you forgot to bind the imageView.

try
 {
    ImageView imageView = (ImageView) findViewById(R.id.Yourimageview);
    String imageName = "model_" + uv.categoryID;
    int id = context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
    imageView.setImageResource(id);
 }
 catch(Exception ex)
 {
     Log.e(TAG, ex);
 }
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31