简体   繁体   中英

Android Unable to create directory on Internal Storage

I have an app that downloads all the images from a URL and saves it to a hidden folder in the device. It works if the phone has an external SD card, but otherwise the app crashes. So I'm trying to convert my code to store images in internal memory.

Even though I read many existing questions, I couldn't solve my problem. I don't know if it can be ".setDestinationInExternalPublicDir" in my "request.setAllowedNetworkTypes" cause of the problem, can it be? How should I change my code?

I also tried using getDataDirectory or getFilesDir () but I still have the exception:

java.lang.IllegalStateException: Unable to create directory

This is my current code that works with phones that have an external SD card:

public class ImagesDownloader {

private static File imageDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + ".Photo");
//or private static File imageDirectory; 

public static void downloadImages(Context context, List<MyList> imageList) {

        //here I tried to change the code like that (without success):
        //File imageDirectory = new File(Environment.getDataDirectory() + File.separator + ".Photo");
        //or
        //File imageDirectory = new File(context.getFilesDir() + File.separator + ".Photo");

        if (!imageDirectory.exists()) {
            if (!imageDirectory.mkdirs()) {
                Log.d("App", "failed to create directory");
            }
        }

        if(getImageFolderSize()==0){
            Iterator<MyList> iterator = imageList.iterator();
            while (iterator.hasNext()) {
                MyList MyList = iterator.next();
                String fileName = MyList.getFilename();
                String imgurl = "https://.../media/MyList/" + fileName;

                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);

                File imageFile = new File(Environment.getExternalStoragePublicDirectory(
                        imageDirectory.getPath()) + "/" + fileName);

                //and here how I wanted to change the code (without success):
                //File imageFile = = new File(imageDirectory.getPath() + "/" + fileName);

                if (!imageFile.canRead()) {

                    DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imgurl));

                    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                            .setAllowedOverRoaming(false)
                            .setTitle(fileName)
                            .setDescription("file description")
                            .setDestinationInExternalPublicDir(imageDirectory.getPath(), fileName)
                            .setVisibleInDownloadsUi(true);

                    BroadcastReceiver onComplete = new BroadcastReceiver() {
                        public void onReceive(Context ctxt, Intent intent) {
                        }
                    };

                    context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                    if (downloadManager != null) {
                        downloadManager.enqueue(request);
                    }
                }
            }
        }
    }

    public static BitmapDescriptor getImgefromDeviceFolder(String fileName){

        File imageFile = new File(Environment.getExternalStoragePublicDirectory(
                imageDirectory.getPath()) + "/" + fileName);

        if (imageFile.canRead()) {
            Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
            return BitmapDescriptorFactory.fromBitmap(myBitmap);

        }
        return null;
    }

    static int getImageFolderSize(){

        File directory = Environment.getExternalStoragePublicDirectory(imageDirectory.getPath());
        if(directory.exists()){
            File[] files = directory.listFiles();
            if(files!=null){
                return files.length;
            }
        }
        return 0;
    }
}

I hope you can forgive me if I make some big mistakes, it's the first time I work with file archiving

This code is for one image and it works.

you can test it and change it for your image list.

  public static void downloadImages(Context context, String fileName ) {
    String storagePath = Environment.getExternalStorageDirectory()
        .getPath()
        + "/Directory_name/";
    //Log.d("Strorgae in view",""+storagePath);
    File f = new File(storagePath);
    if (!f.exists()) {
      f.mkdirs();
    }
    //storagePath.mkdirs();
    String pathname = f.toString();
    if (!f.exists()) {
      f.mkdirs();
    }
    //                Log.d("Storage ",""+pathname);
    DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
    String imgurl = "https://.../media/MyList/" + fileName;
    Uri uri = Uri.parse(imgurl);
      DownloadManager.Request request = new DownloadManager.Request(uri);
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

      request.setDestinationInExternalPublicDir("", uri.getLastPathSegment());
      Long referese = dm.enqueue(request);

      Toast.makeText(context, "Downloading...", Toast.LENGTH_SHORT).show();

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM