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");