5

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.

Rafiq
  • 2,000
  • 2
  • 21
  • 27

1 Answers1

10

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

Community
  • 1
  • 1
Rajesh
  • 15,724
  • 7
  • 46
  • 95
  • How can I access files those are in external storage? – Rafiq May 30 '12 at 07:29
  • I want to like mInputStream = getAssets().open("07.gif"); that display the image on onDraw(). but above answer give InputSteam that does not show on view. – Rafiq May 30 '12 at 07:47
  • Are you getting any exceptions? – Rajesh May 30 '12 at 07:49
  • I am getting 'divided by zero' exception i.e mMovie.duration(); gives me 0 value where Movie mMovie = Movie.decodeStream(mInputStream); – Rafiq May 30 '12 at 07:54
  • I have updated the answer to include debug information to help point out the problem. You should also take a look at the documentation to figure out how to use the APIs. – Rajesh May 30 '12 at 07:59
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/11913/discussion-between-rafiq-and-rajesh) – Rafiq May 30 '12 at 08:02