列出SD卡上的文件夹内容

时间:2018-12-02 11:40:19

标签: android jave

我试图在sdcard/myaudio上的特定文件夹中显示mp3文件,我发现了以下示例:

How to list all files and folders locating on sd card

我用第一种方法写了sdcard名称和文件夹,但是应用程序崩溃了

这是我到目前为止所做的

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));

}

请一些帮助。

更新

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));
}

}

2 个答案:

答案 0 :(得分:0)

您的file.listFiles();可能为空。发生这种情况的原因可能是文件夹为空或特定的文件夹不存在。

您可以使用以下方法检查文件夹是否已经存在,否则请创建它。

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

通过添加以下空检查,可以避免文件夹为空时的崩溃

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

答案 1 :(得分:0)

您的应用似乎无权读取外部存储。
写下:

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

位于<applicationmanifest.xml标记的前面
声明如下:

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

而不是在类级别(在onCreate()之前)在onCreate()内部,以使其在您的活动课程中的任何地方都可见。
创建此方法:

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));       
}

并且在onCreate()中只有以下代码:

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);
    }
}

这样,如果您的应用尚未被授予,它将请求必要的许可。
现在,您将通过覆盖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();
            }
        }
    }
}

在用户接受或不授予您的应用权限之后,将调用上述方法。
因此,fillList()将在您的应用已获得许可或在用户授予许可后执行。如果用户未授予许可,则不会执行该操作。
编辑
在您发布的onCreate()方法中,没有setContentView()。为什么?
Edit2
在您的代码中,您具有:

private void checkAndCreateDirectory() {
}

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

删除1号并从2号中删除String dirName