3

I don't know why decodeFile doesn't work when the param point to a file inside asset folder.

     // Load images from the file path
    String[] dir = null;
    try {
        dir = GenericMainContext.sharedContext.getAssets().list("drawable");
       // dir Log => [ic.png, ic_info_dark.png, ic_launcher_default.png]
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    for (String uri : dir){ 
        // do your stuff here
        if (uri!=null) {
            Bitmap bitmap = null;
            try {
                bitmap = BitmapFactory.decodeFile("file:///android_asset/drawable/"+uri);               } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

Any explanation ?

TooCool
  • 10,598
  • 15
  • 60
  • 85
  • *Any explanation ?* yes, `fileName` doesn't exist in assets ... – Selvin Jul 08 '15 at 13:31
  • I checked the `fileName` exist ;) – TooCool Jul 08 '15 at 13:32
  • no, it doesn't ... I got more rep ... I win ... or you will prove that it exists ... – Selvin Jul 08 '15 at 13:33
  • get look here https://drive.google.com/file/d/0B7MJlMguOqDzX014YXJNb0FTNVU/view?usp=sharing – TooCool Jul 08 '15 at 13:38
  • I believe this is what you're looking for: http://stackoverflow.com/questions/6013029/android-decodefile-always-returns-null-for-file-in-internal-storage – Bun Jul 08 '15 at 13:39
  • @Abdellah one more thing ... show us what is in the `fileName` before you called your code ... also where are you using it? as a field? or in some method ? method of what class? – Selvin Jul 08 '15 at 13:42
  • @Selvin check my edit – TooCool Jul 08 '15 at 13:58
  • you know that `GenericMainContext.getContext().xxxx` may trow NPE then bitmap will be null ? .... my guess is that the all is because `GenericMainContext.sharedContext` and `GenericMainContext.getContext()` .... instead of using context passed via parameter ... – Selvin Jul 08 '15 at 14:04
  • I have 2 years of experience I think I will not miss this ;) – TooCool Jul 08 '15 at 14:06
  • 1
    Don't prefix with `file:///android_asset/`, use use `getAssets().open("drawable/"+uri)` @Abdellah – Dahlgren Jul 08 '15 at 14:09

1 Answers1

5

file:///android_asset/ is used by WebView to load assets. To load assets programmatically use the getAssets() method which returns an AssetMAnager on a Context object such as an Activity. The open(filename) will return a InputStream to your asset file. The following will create a Bitmap from your asset file fileName inside an Activity,

BitmapFactory.decodeStream(getAssets().open(fileName))
Dahlgren
  • 781
  • 4
  • 13