0

I want to save a bitmap as jpg file to my SDcard when a button is pressed. When I run the following code i get no error, but when I check the SDcard on the phone, no file is created. What am I doing wrong ?

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
            }

            String root = Environment.getExternalStorageDirectory().toString();
            //String root = System.getenv("SECONDARY_STORAGE");
            File myDir = new File(root + "/Screenshots");
            myDir.mkdirs();
            Random generator = new Random();
            int n = generator.nextInt(10000);
            String fname = n+".jpg";
            File file = new File(myDir, fname);
            Log.d("DD",""+file);
            if (file.exists()) {
                file.delete();
            }
            try {
                FileOutputStream out = new FileOutputStream(file);
                rBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

I have the permission in the manifest, but still no file is generated:

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

I have done some research that suggest getExternalStorageDirectory() does not give the path to SDcard, but the following alternative gives null:

String root = System.getenv("SECONDARY_STORAGE");

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • Why you are deleting a file and saving bitmap. – Jyoti JK May 15 '18 at 12:07
  • Use `if (!file.exists()) { file.createNewFile(); }` – Jyoti JK May 15 '18 at 12:08
  • Just deleting existing file if the same filename exists. – petrojelly May 15 '18 at 12:09
  • There should be a file, if you want to edit it. If you delete an existing file, There is no file in that path so you can't edit it. Try using the above code – Jyoti JK May 15 '18 at 12:11
  • just tried it but still not seeing any file: try {file.createNewFile(); FileOutputStream out = new FileOutputStream(file); rBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);out.flush();out.close();} catch (Exception e) {e.printStackTrace();} – petrojelly May 15 '18 at 12:13
  • Are you getting any exception? – Jyoti JK May 15 '18 at 12:13
  • no exception at all. This is in my log if i keep pressing the button: D/DD: /storage/emulated/0/Screenshots/149.jpg I/zygote64: Do full code cache collection, code=245KB, data=163KB I/zygote64: After code cache collection, code=165KB, data=102KB D/DD: /storage/emulated/0/Screenshots/5271.jpg I/zygote64: Do partial code cache collection, code=228KB, data=179KB After code cache collection, code=228KB, data=179KB Increasing code cache capacity to 1024KB Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals() D/DD: /storage/emulated/0/Screenshots/2345.jpg – petrojelly May 15 '18 at 12:16
  • https://stackoverflow.com/questions/32789157/how-to-write-files-to-external-public-storage-in-android-so-that-they-are-visibl – CommonsWare May 15 '18 at 12:24
  • Thanks but still don't see any file. I added the following after out.close(): MediaScannerConnection.scanFile(activity, new String[]{file.getAbsolutePath()},new String[] {null}, null); activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)); – petrojelly May 15 '18 at 12:42
  • You are not saving to an SD card but to Environment.getExternalStorageDirectory().. You should look at the right place first. Please post logs in a normal way in your post. Not in a comment. – greenapps May 15 '18 at 13:07
  • `myDir.mkdirs();` Do not call mkdirs() blindly. Replace by `if ( !myDir.exists()) if ( !myDir.mkdirs(){Toast ( ... could not create directory ...); return;}` – greenapps May 15 '18 at 13:09
  • `if (file.exists()) { file.delete(); }` That is not needed. You also dont have to create a new file (as suggested here) as the new FileOutputStream will delete and create the file. – greenapps May 15 '18 at 13:11
  • `Thanks but still don't see any file. ` It looks if you are abusing the Gallery app to see if your file is there. Wrong! You should instead use a file explorer app on your device and look in the right folder/path. Is the directory created? – greenapps May 15 '18 at 13:41
  • `have the permission in the manifest` Ok. But that is not enough for Android 6+ as you can read every day here. – greenapps May 15 '18 at 13:43

1 Answers1

0

Found the answer as pointed out by @CommonsWare that's to call MediaScannerConnection.scanFile, so MediaStore can discover the file and list them in file explorer. Also suggested by @greenapps the files are in the external storage 0, not in the SDcard.

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            }

            String root = Environment.getExternalStoragePublicDirectory("").toString();
            //String root = System.getenv("SECONDARY_STORAGE");
            File myDir = new File(root + "/Screenshots");
            if (!myDir.exists())
                if (!myDir.mkdirs())
                    {Toast.makeText(activity, "make dir failed.", Toast.LENGTH_SHORT).show(); return;}
            Random generator = new Random();
            int n = generator.nextInt(10000);
            String fname = n+".jpg";
            File file = new File(myDir, fname);
            Log.d("DD",""+file);
            try {
                FileOutputStream out = new FileOutputStream(file);
                rBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            //add mediastore discovery
            MediaScannerConnection.scanFile(activity, new String[] {file.getAbsolutePath()},new String[] {null}, null);
        }
    }