androidassetsandroid-assetsandroid-assetmanager

List of files in assets folder and its subfolders


I have some folders with HTML files in the "assets" folder in my Android project. I need to show these HTML files from assets' sub-folders in a list. I already wrote some code about making this list.

lv1 = (ListView) findViewById(R.id.listView);
// Insert array in ListView

// In the next row I need to insert an array of strings of file names
// so please, tell me, how to get this array

lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, filel));
lv1.setTextFilterEnabled(true);
// onclick items in ListView:
lv1.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        //Clicked item position
        String itemname = new Integer(position).toString();  
        Intent intent = new Intent();
        intent.setClass(DrugList.this, Web.class);
        Bundle b = new Bundle();
        //I don't know what it's doing here
        b.putString("defStrID", itemname); 
        intent.putExtras(b);
        //start Intent
        startActivity(intent);
    }
});

Solution

  • private boolean listAssetFiles(String path) {
    
        String [] list;
        try {
            list = getAssets().list(path);
            if (list.length > 0) {
                // This is a folder
                for (String file : list) {
                    if (!listAssetFiles(path + "/" + file))
                        return false;
                    else {
                        // This is a file
                        // TODO: add file name to an array list
                    }
                }
            } 
        } catch (IOException e) {
            return false;
        }
    
        return true; 
    } 
    

    Call the listAssetFiles with the root folder name of your asset folder.

        listAssetFiles("root_folder_name_in_assets");
    

    If the root folder is the asset folder then call it with

        listAssetFiles("");