0

I have some images in my assets folder, and I would like to load them into a ListView by using a SimpleAdapter.

I am referencing the images by their filenames, like: "my_image.jpg".

Here is some code:

ListView lv = (ListView) findViewById(R.id.list);
rows = new ArrayList<Map<String, Object>>();
    for (String s : imageNames) {
        rows.add(createRow(s));
    }

SimpleAdapter adapter = new SimpleAdapter(
            this, 
            rows, 
            R.layout.card_list_row, 
            new String[] {"Image"}, 
            new int[] {R.id.list_row_image});
    lv.setAdapter(adapter);

And the createRow method:

private Map<String, Object> createCardRow(String s) {
    Map<String, Object> row = new HashMap<String, Object>();
    row.put("Image", "file:///android_asset/" + s + ".jpg");
    return row;
}

When I execute this, I get the following error:

02-12 20:01:22.615: I/System.out(17876): resolveUri failed on bad bitmap uri: file:///android_asset/my_image.jpg

And a FileNotFoundException. I obviously know that that image does exist in the assets folder. How can I reference it correctly?

S L
  • 409
  • 2
  • 6
  • 15

2 Answers2

0

Please use a AssetManager

Using a hardcoded absolute path is never a good practice no matter it works or not.

And there're lots of source examples on web, please google for it.

EDIT:

you see that there's a open method in assetManager which returns a InputStream for the specified file resource. Then you can use decodeStream to get a Bitmap object.

Once you need an image, you can use above steps. As you can find an example easily, I won't show it here.

suitianshi
  • 3,300
  • 1
  • 17
  • 34
  • I am using a database containing the filenames of the images stored in the assets folder. Do you think there is a better way? – S L Feb 13 '14 at 02:33
  • Database is good at managing a large number of objects or data set that may change (add/delete) often. The management implementation should depend on your requirements. For example, if you only have up to ten images, then there's no need to use a "heavy" database at all. – suitianshi Feb 13 '14 at 02:51
  • I have about 400 objects stored in the database, and each has a reference to an image. – S L Feb 13 '14 at 02:59
  • I think it is ok then. – suitianshi Feb 13 '14 at 03:19
  • So how would I integrate the AssetManager? – S L Feb 13 '14 at 03:20
0

Hello Try using below function.

public void loadDataFromAsset(String imagenamefomdb) {

        try {



            InputStream ims = getAssets().open(imagenamefomdb);
            Drawable d = Drawable.createFromStream(ims, "image");
            imageview.setImageDrawable(d);
            ims.close();

        } catch (IOException ex) {
            return;
        }

    }

Hope it works for you

Mayuri Ruparel
  • 694
  • 2
  • 11
  • 36