13

I create some folders into assets. Each folder contains files that I would like to list. I am using following code but I always get a null value for fileList. Thank you.

I used, listFiles("/assets/images/","nothing");

private void listFiles(String dirFrom, String dirTo) {


        File f = new File(dirFrom);

        String fileList[] = f.list();

            if (fileList != null)
            {   
                for ( int i = 0;i<fileList.length;i++)
                {
                    Log.d("",fileList[i]); 
                }
            }
    }    
Jaume
  • 3,672
  • 19
  • 60
  • 119

2 Answers2

27

You'll probably want to do this:

private void listFiles(String dirFrom) {
        Resources res = getResources(); //if you are in an activity
        AssetManager am = res.getAssets();
        String fileList[] = am.list(dirFrom);

            if (fileList != null)
            {   
                for ( int i = 0;i<fileList.length;i++)
                {
                    Log.d("",fileList[i]); 
                }
            }
    }

Also your function call should be: listFiles("images"); if you want to list images.

pleerock
  • 18,322
  • 16
  • 103
  • 128
user
  • 86,916
  • 18
  • 197
  • 190
  • how to get the file name? – Shihab Uddin May 09 '14 at 20:29
  • @The_Lazy_Man Isn't the array of strings returned by the `Assetmanager.list()` method what you want? – user May 10 '14 at 05:02
  • yes, you are right. But I am facing new problem. can't get the resource ID to initialize an ImageView. Because asset file not provide me the that. Thanks for you reply. :) – Shihab Uddin May 10 '14 at 08:47
  • @The_Lazy_Man Files in assets don't get ids, you're forced to use the methods of the `AssetManager` and build the bitmap on your own(and then set it on the `ImageView`). – user May 10 '14 at 08:51
  • ya, I am going on your way. will give you feedback after that. – Shihab Uddin May 10 '14 at 08:53
  • it's rather: String[] fileList = am.list(dirFrom); also, fileList is always not null, even if no files are found or path is not found, but Exception might be raised. So should be surrounded by try catch. – Raphael C Jul 29 '14 at 08:31
7

Simplest would surely be this:

String[] fileList = getAssets().list("images");
Mike Redrobe
  • 1,248
  • 13
  • 12