android get Bitmap or sound from assets

Val picture Val · Dec 14, 2011 · Viewed 50.9k times · Source

I need to get Bitmap and sound from assets. I try to do like this:

BitmapFactory.decodeFile("file:///android_asset/Files/Numbers/l1.png");

And like this:

getBitmapFromAsset("Files/Numbers/l1.png");
    private Bitmap getBitmapFromAsset(String strName) {
        AssetManager assetManager = getAssets();
        InputStream istr = null;
        try {
            istr = assetManager.open(strName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(istr);
        return bitmap;
    }

But I get just free space, not image.

How to do this?

Answer

Warpzit picture Warpzit · Dec 14, 2011
public static Bitmap getBitmapFromAsset(Context context, String filePath) {
    AssetManager assetManager = context.getAssets();

    InputStream istr;
    Bitmap bitmap = null;
    try {
        istr = assetManager.open(filePath);
        bitmap = BitmapFactory.decodeStream(istr);
    } catch (IOException e) {
        // handle exception
    }

    return bitmap;
}

the path is simply your file name fx bitmap.png. if you use subfolder bitmap/ then its bitmap/bitmap.png