0

I have a question. I know I can store an image as byte array in SQLite database. But this needs some extra CPU work, so I tried to store only the id (R.drawable.myImage).

I stored it as an integer and I can retrieve it back. I am setting my image into imageview like this:

ivSportIcon.setImageResource(getItem(i).getIcon());

But I get an error:

Resources$NotFoundException: Resource ID #0x8

Is this a wrong way? Should I store my image as a byte array? Thank you in advance!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Zapdos
  • 617
  • 1
  • 6
  • 23

2 Answers2

0

I do not know how you are storing the resource ID, but 0x8 is not a resource ID.

Beyond that, bear in mind that resource IDs change with each build, and so the resource ID that you save today will be different tomorrow.

Instead, store some other identifier in the database, that you can use to decide which of your drawables to use.

The only reason to store the actual image data in the database would be if you plan to change the images in the future and you want the user to be able to use the old images that happen to be associated with database entries.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • No 0x8 is a valid resource id in R.java file. Other than that, you are right. I may not need to save images into db for my app. And also I didn't know resource id's are changing every time. I will wait some other replies, then I may accept this as an answer. Until than, you can add more information about this topic too. – Zapdos Jun 24 '17 at 21:09
0

You could store the name of the Drawable as a String instead, and use this method to retrieve its id:

public static int getResourceIdForName(Context context, String drawableName) {
    final Resources res = context.getResources();
    final String packageName = context.getPackageName();
    return res.getIdentifier(drawableName , "drawable", packageName);
}

This is a little inflexible however, as if you decide to change the name of your drawable in future, then you will also need to change the name in the database.

PPartisan
  • 8,173
  • 4
  • 29
  • 48