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 1:
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("");
Solution 2:
try this it will work in your case
f = getAssets().list("");
for(String f1 : f){
Log.v("names",f1);
}
The above snippet will show the contents of the asset root.
For example... if below is the asset structure..
assets
|__Dir1
|__Dir2
|__File1
Snippet's output will be .... Dir1 Dir2 File1
If you need the contents of the Directory Dir1
Pass the name of Directory in the list function.
f = getAssets().list("Dir1");
Solution 3:
Hope This Help:
following code will copy all the folder and it's content and content of sub folder to sdcard location:
private void getAssetAppFolder(String dir) throws Exception{
{
File f = new File(sdcardLocation + "/" + dir);
if (!f.exists() || !f.isDirectory())
f.mkdirs();
}
AssetManager am=getAssets();
String [] aplist=am.list(dir);
for(String strf:aplist){
try{
InputStream is=am.open(dir+"/"+strf);
copyToDisk(dir,strf,is);
}catch(Exception ex){
getAssetAppFolder(dir+"/"+strf);
}
}
}
public void copyToDisk(String dir,String name,InputStream is) throws IOException{
int size;
byte[] buffer = new byte[2048];
FileOutputStream fout = new FileOutputStream(sdcardLocation +"/"+dir+"/" +name);
BufferedOutputStream bufferOut = new BufferedOutputStream(fout, buffer.length);
while ((size = is.read(buffer, 0, buffer.length)) != -1) {
bufferOut.write(buffer, 0, size);
}
bufferOut.flush();
bufferOut.close();
is.close();
fout.close();
}