tadvas tadvas - 4 months ago 10
Android Question

Saving image\file

The issue is to save image to the storage
This code worked fine, but not with Android 6 and N

What do I need to fix here?
Or as an option - using another example for saving to internal\external files

public void saveImage(Bitmap icon) {

File ff;
File file = new File(android.os.Environment.getExternalStorageDirectory(), "Folder Name");

ff = new File(file.getAbsolutePath() + file.separator + imageName + ".jpg");
if(ff.exists()){

Log.i("sharing", "File exist SD");
} else{
try {
File f = null;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

if (!file.exists()) {
file.mkdirs();
}
Log.i("sharing", "File exist Internal");
f = new File(file.getAbsolutePath() + file.separator + imageName + ".jpg");
}
FileOutputStream ostream = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 10, ostream);
ostream.close();

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

}


And permissions from Manifest:

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

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


Thanx

Answer

I added permissions for android sdk > 22

This code works perfectly

 if (ContextCompat.checkSelfPermission(HomeActivity.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {                                              
                            ActivityCompat.requestPermissions(HomeActivity.this,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},23
                                    );

                    }