Can't Write File On Sd Card In Android App
I am unable to write file on physical SD card. I want to ask user for permission to write to whole SD card. User grants the permission. Now I want to create file in specific direc
Solution 1:
string targetUri = uriWithPermission + "MyDir/MyFile.MyExt"; // MyDir exists
Even if MyDir
exists your code will not work as you have seen as it is not the right uri for a file there.
Also if the user had choosed the MyDir directory and your coude would look like
string targetUri = uriWithPermission + "/MyFile.MyExt";
your code, using an outputstream to create a file, still would not work.
Instead you should use DocumentFile
to obtain an instance for the choosen directory. After that you can use DocumentFile.createFile()
to create a subdirectory or file.
You do not need the usual permissions in manifest and runtime for this.
Solution 2:
You have to give runtime permission
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
//File write logic herereturntrue;
} else {
ActivityCompat.requestPermissions(this, newString[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE)
}
Solution 3:
check following code it would be help you to understand file save in memory.
@OverridepublicvoidonActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
// Show the thumbnail on ImageViewpreviewMedia();
} elseif (requestCode == REQUEST_GALLERY_PHOTO && resultCode == RESULT_OK) {
// Show the thumbnail on ImageViewtry {
imageUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(imageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mCurrentPhotoPath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(compressImage(mCurrentPhotoPath));
preview_imageview.setImageBitmap(bitmap);
} catch (Exception e) {
e.getMessage();
}
// ScanFile so it will be appeared on GalleryMediaScannerConnection.scanFile(getActivity(),
newString[]{imageUri.getPath()}, null,
newMediaScannerConnection.OnScanCompletedListener() {
publicvoidonScanCompleted(String path, Uri uri) {
}
});
}
}
Post a Comment for "Can't Write File On Sd Card In Android App"