当我尝试访问手机的外部存储器时,应用程序崩溃

时间:2018-07-18 10:48:55

标签: java android directory

我创建了一个简单的应用程序,该应用程序尝试访问手机的外部存储文件并将其显示在警报框中,代码如下所示。

btnShowDeviceFolders.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            CharSequence items[];

            final List<String> list = new ArrayList<String>();
            final File path =
                    Environment.getExternalStoragePublicDirectory
                            (
                                    //Environment.DIRECTORY_PICTURES
                                    Environment.DIRECTORY_DCIM
                                    //File.separator +"/"
                            );
            if(!path.exists())
            {
                //path.mkdirs();
             System.out.println("No file found");
            }
            String[] files = path.list();
            if (files.length == 0) {
                //System.out.println("The directory is empty");

            } else {
                for (String aFile : files) {

                    //System.out.println(aFile);
                    list.add(aFile);
                }
            }
            items = files;

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Select Project Folder");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {

                    Toast.makeText(getApplicationContext(),list.get(item),Toast.LENGTH_LONG).show();
                                        }
            });
            builder.show();
        }
    });

但是此代码在模拟器上运行良好,它列出了我存在的文件夹,但是当我构建apk并在手机上对其进行测试时,它崩溃了(我正在使用android Oreo进行测试)。 Stacktrace没有给出任何错误 enter image description here  我该怎么做才能克服这个问题。

3 个答案:

答案 0 :(得分:1)

授予android_manifest.xml文件中的外部存储器权限。

答案 1 :(得分:0)

您必须给android.permission.READ_EXTERNAL_STORAGE运行时间。 here is the tutorial

答案 2 :(得分:0)

您仅在清单文件中授予了权限,而这还不足以授予运行时权限。

 if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            //Show Information about why you need the permission
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Need Storage Permission");
            builder.setMessage("This app needs storage permission.");
            builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.show();
        } else if (permissionStatus.getBoolean(Manifest.permission.WRITE_EXTERNAL_STORAGE,false)) {
            //Previously Permission Request was cancelled with 'Dont Ask Again',
            // Redirect to Settings after showing Information about why you need the permission
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Need Storage Permission");
            builder.setMessage("This app needs storage permission.");
            builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    sentToSettings = true;
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                    Toast.makeText(getBaseContext(), "Go to Permissions to Grant Storage", Toast.LENGTH_LONG).show();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.show();
        } else {
            //just request the permission
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
        }

        SharedPreferences.Editor editor = permissionStatus.edit();
        editor.putBoolean(Manifest.permission.WRITE_EXTERNAL_STORAGE,true);
        editor.commit();


    } else {
        //You already have the permission, just go ahead.
        proceedAfterPermission();
    }