fellow programmers! I'm new... hope you can help!
So. I'm currently developing an application that allows users to choose four different images from a set of images that I have saved in my res/drawable/ folder, and then save those choices as an entry in a database.However, I then need to be able to redisplay those four images when the user asks for them, and I'm not sure what the best way of storing the images is since my current setup isn't going to work for me in the future.
Right now, I have it working so that I actually insert the R.java int identifiers into the database for each of the images, so the database has four columns: img1(int), img2(int), img3 (int), img4 (int). Then when I write a query, I just use those values in place of R.drawable.someImage.
It works fine. Except... when I add new images to my res/drawable folder, all of 开发者_C百科the drawable ids get changed! Then the ids I have in the database are wrong, and some pull up the wrong images, and some throw NullPointerExceptions!
This is a problem, because I want to be able to update the app with new images after the users download it. How should I be storing these images so that they can be dynamically chosen, but then be reliably be referenced again?
This is a problem, because I want to be able to update the app with new images after the users download it.
I don't quite understand this - if you are going to distribute new images 'after' the users download your app then the new images are never going to have resource ids (as found in R.java) as these are auto-generated as part of the build process.
Do you really mean this or do you intend to update the app with new images and have the users download it again?
If you are going to update the app with new images periodically and have the users download the updated app, you can find the resource id at runtime using...
int resId = getResources.getIdentifier("img1", "drawable", "com.mycompany.mypackagename");
At this point, of course, you'll need to know the names of all the drawables although this could be achieved with a string array in your res/values/strings.xml.
If, however, you want to add new images without the need for the user updating the app, I'd think about maintaining an image directory (on the SD card for example). This way, you would simply just need to store the path to the image files in the DB.
Resources can be accessed as raw data: use AssetManager.open(..) Then you can use BitmapFactory.decodeStream(..) to create a Bitmap from the data stream.
So you can just save filenames of images and instantiate Bitmaps via above commands.
精彩评论