How to create folder in external storage and check

2019-09-05 02:28发布

问题:

I want to create a folder on click of photo's layout. And on click of layout new folder created should get open if it is empty it should show the toast or it should get open with images. For this I have created a new file and I am doing a scan for files, it is throwing a null pointer exception for the array of files.

  String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path,"/MeaVita");



File file1 = new File(Environment.getExternalStorageDirectory().getPath() + "/MeaVita");

File[] listFile = file1.listFiles();



    photosLayout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {


            checkFilePermissions();


              if (!dir.isDirectory()) {
                 dir.mkdirs();
              }


            if (listFile.length == 0) {
                    Toast.makeText(MainActivity.this, "The folder is empty.", Toast.LENGTH_SHORT).show();
                } else {

                    new MainActivity.SingleMediaScanner(MainActivity.this, listFile[0]);
                }

        }
    });

methods

    public class SingleMediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {

    private MediaScannerConnection mMs;
    private File mFile;

    public SingleMediaScanner(Context context, File f) {
        mFile = f;
        mMs = new MediaScannerConnection(context, this);
        mMs.connect();
    }

    public void onMediaScannerConnected() {
        mMs.scanFile(mFile.getAbsolutePath(), null);
    }

    public void onScanCompleted(String path, Uri uri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(uri);
        startActivity(intent);
        mMs.disconnect();
    }

}

private void checkFilePermissions() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        int hasWriteExternalStoragePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_CODE_ASK_PERMISSIONS);
        }
    }
}

Log :

FATAL EXCEPTION: main
                                                                        Process: com.example.siddhi.meavita, PID: 15025
                                                                        java.lang.NullPointerException: Attempt to get length of null array
                                                                            at com.example.siddhi.meavita.Activities.MainActivity$2.onClick(MainActivity.java:119)
                                                                            at android.view.View.performClick(View.java:5201)

EDIT:

  photosLayout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {


            String folder_main = "MeaVita";
            File dir = new File(Environment.getExternalStorageDirectory(),folder_main);


            checkFilePermissions();

            if (!dir.exists()) {
                dir.mkdirs();
            }

            File[] listFile = dir.listFiles();

            if (listFile.length == 0) {
                Toast.makeText(MainActivity.this, "The folder is empty.", Toast.LENGTH_SHORT).show();
            } else {

                new MainActivity.SingleMediaScanner(MainActivity.this, listFile[0]);
            }

        }
    });

This code works now , but it dose not ask for the permission then also it creates the folder. How?

Not getting what's going wrong help please..

回答1:

Try this,

String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path,"/MeaVita");
 if (!dir.isDirectory()) {
             dir.mkdirs();
          }

add following line your manifest.xml

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

this may helps you.

EDIT 1:

It seems you are access empty/null File[] . you may modify the code structure like,

 String path = Environment.getExternalStorageDirectory().toString();
 File dir = new File(path,"/MeaVita");

 photosLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        checkFilePermissions();
          if (!dir.isDirectory()) {
             dir.mkdirs();
          }

        File file1 = new   File(Environment.getExternalStorageDirectory().getPath() + "/MeaVita");
        File[] listFile = file1.listFiles();

          if (listFile.length == 0) {
                Toast.makeText(MainActivity.this, "The folder is empty.", Toast.LENGTH_SHORT).show();
            } else {

                new MainActivity.SingleMediaScanner(MainActivity.this, listFile[0]);
            }

    }
});


回答2:

String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path,"/MeaVita");

photosLayout.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

 if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
     if (!dir.isDirectory()) {
         dir.mkdirs();
     }


     if (listFile.length == 0) {
                Toast.makeText(MainActivity.this, "The folder is empty.",Toast.LENGTH_SHORT).show();
            } else {
                new MainActivity.SingleMediaScanner(MainActivity.this, listFile[0]);
            }
    }
  } else {
        checkFilePermissions();

} });