开发者

reading image path from a database

I'm stuck in something that I'm sure rather easy

I have a field in the database that I stored the image name in it, ex 'images/e开发者_运维知识库x1.png'

how can I read this into an imageView?? I tried some code in there but can't get it to work

a good example is highly


You cannot set the image file directly as the resource for your ImageView (that only takes the resource ID). Instead you will have to use a BitmapFactory to decode it and then use setImageBitmap

EDIT :

Your problem is that there is no way for you to map the name of the image file with the resource ID in the code. The easier way is probably for you to put together a map table. First put your image files in the drawable folder (res/drawable/ex1.png...) and then, do something like this in your code :

Map map = new HashMap();

// Add key/value pairs to the map
map.put("images/ex1.png", new Integer(R.drawable.ex1));
map.put("images/ex2.png", new Integer(R.drawable.ex2));
// do that for all the images....

String image_name = // query to your database
ImageView the_image_to_change = // findViewById(...)
if (map.containsKey(image_name)) {
    the_image_to_change.setImageResource((Integer)(map.get(image_name)).intValue()); // not sure so much is necessary...
}


If you're storing this in your /res/ folder, you need to use a ContentProvider in order to get access to this resource. You shouldn't be accessing resources directly unless you're downloading them externally from the app.

Hope this helps.


myImageView.setImageBitmap(BitmapFactory.decodeFile(myFilePathString));

Your issue is that your file path does not include the root of the device's file system. You have to add this to the beginning of your file path string. This depends on how you save the images. So...

To acquire the appropriate file path to a file on the sd card:

File sdCard = Environment.getExternalStorageDirectory(); 
String filePath = sdCard.getAbsolutePath() + imageFilePath;

If you're saving your images to internal memory, your app is automatically given a folder to save files to and they will be located there. To find the root to that path use getFilesDir(). For more information on data storage check out http://developer.android.com/guide/topics/data/data-storage.html.


Use the res/drawable folder. Here's how to load an image from drawable to a Bitmap.

Bitmap myImage = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_image);

More on resources: http://developer.android.com/guide/topics/resources/providing-resources.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜