'List folder content on sdcard

I'm trying to display mp3 files in a specific folder on sdcard/myaudio, I found this example:

How to list all files and folders locating on sd card

I write the sdcard name and folder in the first method, but the app is crashing

this is what I have done until now

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    myList = new ArrayList<String>();

    String root_sd = Environment.getExternalStorageDirectory().toString();
    file = new File(root_sd + "/sdcard/myaudio");
    File list[] = file.listFiles();

    for (int i = 0; i < list.length; i++) {
        myList.add(list[i].getName());
    }

    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, myList));

}

Please some help.

update

public class MainActivity extends ListActivity {
private File file;
String root_sd = Environment.getExternalStorageDirectory().toString();
ArrayList<String> myList = new ArrayList<String>();

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    checkAndCreateDirectory();

    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        fillList();
    } else {
        ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
    }
}

private void fillList() {
    String root_sd = Environment.getExternalStorageDirectory().toString();
    File file = new File(root_sd + "/sdcard/myaudio");
    File list[] = file.listFiles();

    for (int i = 0; i < list.length; i++) {
        myList.add(list[i].getName());
    }

    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myList));
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == 100) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                fillList();
            }
        }
    }
}

private void checkAndCreateDirectory() {
}

public void checkAndCreateDirectory(String dirName){
    File new_dir = new File( root_sd + "/sdcard/myaudio/" );
    if( !new_dir.exists() ){
        new_dir.mkdirs();
    }
}

protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    File temp_file = new File(file, myList.get(position));

    if (!temp_file.isFile()) {
        file = new File(file, myList.get(position));
        File list[] = file.listFiles();

        myList.clear();

        for (int i = 0; i < list.length; i++) {
            myList.add(list[i].getName());
        }
        Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show();
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, myList));
    }
}

@Override
public void onBackPressed() {
    String parent = file.getParent().toString();
    file = new File(parent);
    File list[] = file.listFiles();

    myList.clear();

    for (int i = 0; i < list.length; i++) {
        myList.add(list[i].getName());
    }
    Toast.makeText(getApplicationContext(), parent, Toast.LENGTH_LONG).show();
    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, myList));
}

}



Solution 1:[1]

Your file.listFiles(); may be null. It can happen due to an empty folder or specific folder is not there.

You can use below method to check if the folder is already there otherwise create it.

 public void checkAndCreateDirectory(String dirName){
        File new_dir = new File( rootDir + dirName );
        if( !new_dir.exists() ){
             new_dir.mkdirs();
        }
    }

you can avoid a crash when the folder is empty by adding the following null check

File list[] = file.listFiles(); 
if(list == null) return;

Solution 2:[2]

It seems that your app does not have the permission to read the external storage.
Write this:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

just before the <application tag in your manifest.xml
Put this declaration:

ArrayList<String> myList = new ArrayList<String>();

instead of inside onCreate() at the class level (before onCreate()) to make it visible anywhere in your activity class.
Create this method:

private void fillList() {
    String root_sd = Environment.getExternalStorageDirectory().toString();
    File file = new File(root_sd + "/datanfile");
    File list[] = file.listFiles();

    for (int i = 0; i < list.length; i++) {
        myList.add(list[i].getName());
    }

    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myList));       
}

and in onCreate() have this code only:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);  ???????
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        fillList();
    } else {
        ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
    }
}

This way your app will ask for the necessary permission if it is not already granted.
Now you will get whether the user granted this permission, by overriding onRequestPermissionsResult() :

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == 100) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                fillList();
            }
        }
    }
}

The above method is invoked after the user has accepted or not to grant your app the permission.
So fillList() will be executed if your app has already the permission, or after the user grants the permission. It will not be executed if the user does not grant the permission.
Edit
In the onCreate() method you posted there is no setContentView(). Why?
Edit2
In your code you have:

private void checkAndCreateDirectory() {
}

public void checkAndCreateDirectory(String dirName){
    File new_dir = new File( root_sd + "/sdcard/myaudio/" );
    if( !new_dir.exists() ){
        new_dir.mkdirs();
    }
}

Delete the 1st and remove String dirName from the 2nd

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PushpikaWan
Solution 2