E.Fery E.Fery - 1 month ago 12
Java Question

Counting files in assets subfolders

I have a folder in

assets
folder named
s1
.There are about a hundred text file in it. I want to count how many text files are in that folder.

The application crashes at start up with this error : `

Caused by: java.lang.NullPointerException: Attempt to get length of null array


Here is the code in
MainActivity
:

Integer fileCount = 0;
fileCount = Integer.valueOf(new File("./assets/s1/").listFiles().length);


for(int i=0;i<fileCount;i++) {

Button btn = new Button(this);
btn.setId(i+1);
btn.setText("button "+(i+1));
btn.setLayoutParams(lprams);
final int index = i;
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("TAG", "The index is" + index);
}
});
dynamicview.addView(btn);
}


How to solve that?

Answer

You need to access the assets like this:

fileCount = getResources().getAssets().list("s1").length;

getResources() returns the Resources instance for your app. Calling getAssets() on that returns the AssetManager. Files in the assets do not exist in the file system, so you cannot open and read them like normal files.

Comments