0

I'm storing the image id in sqlite,but when I retrieve the id I got the error android.content.res.Resources$NotFoundException: Resource ID #0x42

So I'm guessing holder.myImg.setImageDrawable(c.getResources().getDrawable(99));

it doesn't work because it waits for a resource not a int

Taking into consideration that image id is stored into sqlite, how do I get the image for setImageDrawable?

What is the best practice for saving images in sqlite?

  • "Taking into consideration that image id is stored into sqlite" – Neither of those is a valid resource ID. How exactly are you saving that value? – Mike M. Aug 31 '19 at 19:34
  • 2
    You should store image uri to your database and get uri from database pass to imageview – Anas Mehar Aug 31 '19 at 19:34
  • You should use setImageResource() instead of setImageDrawable() – Nooruddin Lakhani Aug 31 '19 at 19:35
  • @MikeM. I'm getting the image id like this ` image_id = Integer.parseInt(uriPath.get(uriPath.size() -1).replaceAll("\\D+",""));` but the image I get for preview I set with ` Bitmap thumb = MediaStore.Images.Thumbnails.getThumbnail(resolver, image_id, MediaStore.Images.Thumbnails.MINI_KIND, null); // Set the image in ImageView ImageView im = findViewById(R.id.imgCat); //https://stackoverflow.com/questions/10413659/how-to-resize-image-in-android im.setImageBitmap(thumb);` –  Aug 31 '19 at 19:39
  • I'm also interested in best practice –  Aug 31 '19 at 19:40
  • "I'm getting the image id like this" -- what is this `Uri`? Where did it come from? – CommonsWare Aug 31 '19 at 19:45
  • I'm using intent to get a image from camera or gallery –  Aug 31 '19 at 21:25

3 Answers3

0

Instead of storing the integer id of the drawable in the database store its string id (name).
The reason to avoid the use of the integer id is that it is not guaranteed to be always the same each time you build your project.
The integer ids given to views, drawables etc may change every time you make changes and rebuild.
So if you store the string id (name) of a drawable, say ic_menu_camera, when you retrieve it from the database you can get its integer id by:

int id = context.getResources().getIdentifier("ic_menu_camera", "drawable", context.getPackageName());

and then use safely that id.
context is a valid Context that you must supply.

forpas
  • 160,666
  • 10
  • 38
  • 76
0

there is no way of getting the id, as Mike M said I shouldn't store id there. Best option for now is to store the image as blob

0

1)Load image from patch

 Bitmap myBitmap=  BitmapFactory.decodeFile(prm_FileOrig, null);

2)Use Bitmap.CompressFormat.JPEG to reduce space (optional)

3)Save bitmap in sqlite in a blob field

if you have already implemented the sqlite helper classes in your project it's the best solution, for me.

If you want remain in your "style", a thing like that:

int yourid =getResources().getIdentifier("yourpackagename:drawable/" + 99, null, null);
holder.myImg.setImageResource(yourid);
Bronz
  • 217
  • 3
  • 7