Opening a File from assets folder in android
Asked Answered
W

6

15

I have a .gif file inside the assets folder like this assets/Files/android.gif. when I try to open the file it throws an exception at the second line

AssetManager mngr=getAssets();
InputStream is2=mngr.open("Files/android.gif");

so Is it that I'm trying to open an image file despite that the same code works if I try to open a text file ? what can be the problem here.

Warm answered 19/12, 2009 at 14:18 Comment(0)
B
31

These Lines are working perfectly--

InputStream assetInStream=null;

try {
    assetInStream=getAssets().open("icon.png");
    Bitmap bit=BitmapFactory.decodeStream(assetInStream);
    img.setImageBitmap(bit);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if(assetInStream!=null)
    assetInStream.close();
}

If your image is very big then you should scale your image before decoding it into Bitmap. See How to display large image efficiently

Battat answered 14/12, 2011 at 9:36 Comment(1)
AFIK stream should be closed after useSupermundane
S
4

I suspect you are getting complaints about unhandled exception type IOException. If that's the case, you need to put the call to mgr.open in a try-catch block to handle the exception that may occur when retrieving the InputStream object.

AssetManager mngr = getAssets();
try {
    InputStream is2 = mngr.open("Files/android.gif");
} catch (final IOException e) {
    e.printStackTrace();
}
Shrove answered 19/12, 2009 at 18:38 Comment(0)
D
1

Don't know if things have changed or not but I had an app in Android 1.1 that opened icons to then display them in a view and I did it like so:

BufferedInputStream buf = new BufferedInputStream(mContext.openFileInput(value));
Bitmap bitmap = BitmapFactory.decodeStream(buf);
Dacha answered 19/12, 2009 at 14:29 Comment(0)
C
1

I believe the preferred way to do this is to put your image in the res/drawable directory. Then you can get a Drawable like this:

Drawable d = Resources.getSystem().getDrawable(R.drawable.android);
Clinton answered 19/12, 2009 at 16:43 Comment(0)
A
0

Mina, I had the same problem... I had images and an XML file within "assets" and I could read the XML file but not the images. After a couple of hours of frustration I finally found the solution !

I have posted the solution here: Null-pointer issue displaying an image from assets folder Android 2.2 SDK

Arlon answered 5/5, 2011 at 19:15 Comment(0)
S
0

I do not believe gif is supported automatically on Android. Try a png or jpg with the same code.

Sudbury answered 27/10, 2018 at 23:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.