我正在尝试将图像保存在默认图像位置,并将文件名打印到TextView中。

当我尝试进入目录时,总是在listFiles上获得nullpointerexception。我尝试了几种获取目录路径的方法,但是似乎没有任何效果。

我什至在清单中设置了权限。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

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

    final String NEW_LINE = "\n";

    final Button button = (Button) findViewById(R.id.renameImgBtn);
    final TextView textView = (TextView) findViewById(R.id.textView);

    textView.setMovementMethod(new ScrollingMovementMethod());

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            File camDir = new File("/sdcard/DCIM/"); // wtf is this supposed to be!?

            textView.append(camDir.getAbsolutePath() + NEW_LINE);
            if (camDir == null) {
                textView.append("camDir is null" + NEW_LINE);
            } else {
                textView.append("camDir is not null" + NEW_LINE);

                // get nullpointerexception on listFiles
                File[] files = camDir.listFiles();
                if (files == null) {
                    textView.append("files is null" + NEW_LINE);
                } else {
                    for (final File file : files) {
                        textView.append(file.getName() + NEW_LINE);
                    }
                }
            }
        }
    });
}


我使用的是Nexus 6P,图片在DCIM / Camera /下。

最佳答案

首先,DCIM目录由DIRECTORY_DCIM定义,并且应与Environment.getExternalStoragePublicDirectory()结合使用:

File camDir = Environment.getExternalStoragePublicDirectory(
    Environment.DIRECTORY_DCIM);


其次,就像您在棉花糖设备上一样,如果您以API 23为目标,则必须request dangerous permissions at runtime-READ_EXTERNAL_STORAGE是危险许可,并且必须遵守这些规则。

关于java - 如何在/DCIM/Camera上获取图像文件数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34249132/

10-10 20:09