E.Fery E.Fery - 1 year ago 69
Java Question

Counting files in assets subfolders

I have a folder in

folder named
.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

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.setText("button "+(i+1));
final int index = i;
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.i("TAG", "The index is" + index);

How to solve that?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download