Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open .gif file as InputStream from external storage on android

I am trying to load .gif image from external storage (pictures directory) but I am getting 'file not found exception' using the following code.

    InputStream mInputStream = null;
    AssetManager assetManager = getResources().getAssets();
    try {
        mInputStream = assetManager.open(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath().concat("/01.gif"));          

    } catch (IOException e) {           
        e.printStackTrace();
    }

I have also tested using manually path but got same exception

mInputStream = assetManager.open("file:///mnt/sdcard/Android/data/com.shurjo.downloader/files/Pictures/01.gif");

There is a write/read permission from the SD card in menifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Please help me how can I open a file as InputStream from external storage. Thanks in advance.

Note: I have tested it on emulator and there is a file 01.gif under Pictures folder (please see manual path). I can create directories and put files in those directories but can not able to access those files though Input Stream.

like image 217
Rafiq Avatar asked Dec 28 '22 00:12

Rafiq


1 Answers

AssetManager is for accessing the files in the assets folder of the application package. It cannot be used to access files in the external storage.

You can use the following:

final String TAG = "MyAppTag";

File picturesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = null;
final int readLimit = 16 * 1024;
if(picturesDir != null){
    imageFile = new File(picturesDir, "01.gif");
} else {
    Log.w(TAG, "DIRECTORY_PICTURES is not available!");
}
if(imageFile != null){
    mInputStream =  new BufferedInputStream(new FileInputStream(imageFile), readLimit);
    mInputStream.mark(readLimit);
} else {
    Log.w(TAG, "GIF image is not available!");
}

Please also take a look at the sample code available in getExternalFilesDir

Update from : this

like image 129
Rajesh Avatar answered Jan 03 '23 19:01

Rajesh