Read/Write permission are not triggering in android - android

Hi in the below code When I am trying click it is showing you don't have read and access permission.But in the manifest file I has given those two permission.Both read and write permission are not triggering with my below code.Both the permission I am calling haspermission evry time failing
Can any one help me where I did the mistake.
java:
private static final String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
String modality_name = opportunity.getModality();
if (modality_name.equals("LCS")||modality_name.equals("Ultrasound")||modality_name.equals("DI")) {
// Toast.makeText(mContext, modality_name, Toast.LENGTH_LONG).show();
holder.pdf.setVisibility(View.GONE);
}else {
holder.pdf.setVisibility(View.VISIBLE);
holder.pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!hasPermissions(mContext, PERMISSIONS)) {
Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");
Toast t = Toast.makeText(mContext, "You don't have read access !", Toast.LENGTH_LONG);
t.show();
} else {
File d = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); // -> filename = maven.pdf
String url_path = opportunity.getPdf_link();
///Log.d("url_path", url_path);
String file_name = url_path.substring(url_path.lastIndexOf('/') + 1);
//Log.d("file_name", file_name);
File pdfFile = new File(d, file_name);
Log.v(TAG, "view() Method pdfFile " + pdfFile.getAbsolutePath());
if(pdfFile!=null) {
Uri path = GenericFileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", pdfFile);
Log.v(TAG, "view() Method path " + url_path);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
mContext.startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(mContext, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
// }
}
Log.v(TAG, "view() Method completed ");
// download(v);
//request(v);
}
download(v);
// request(v);
}
public void request(View v) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, 112);
}
public void download(View v) {
Log.v(TAG, "download() Method invoked ");
if (!hasPermissions(mContext, PERMISSIONS)) {
Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");
Toast t = Toast.makeText(mContext, "You don't have write access !", Toast.LENGTH_LONG);
t.show();
} else {
Log.v(TAG, "download() Method HAVE PERMISSIONS ");
String url_path = opportunity.getPdf_link();
Log.d("url_path", url_path);
String file_name = url_path.substring(url_path.lastIndexOf('/') + 1);
Log.d("file_name", file_name);
new DownloadFile().execute(url_path, file_name);
}
Log.v(TAG, "download() Method completed ");
}
});
}
}
// public DragListener getDragInstance() {
// if (mlistener != null) {
// return new DragListener(mlistener);
// } else {
// Log.e("Route Adapter: ", "Initialize listener first!");
// return null;
// }
// }
private class DownloadFile extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
Log.v(TAG, "doInBackground() Method invoked ");
String fileUrl = strings[0];
Log.d("fileurl",fileUrl);
String fileName = strings[1]; // -> maven.pdf
Log.d("fileName",fileName);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File pdfFile = new File(folder, fileName);
Log.v(TAG, "doInBackground() pdfFile invoked " + pdfFile.getAbsolutePath());
Log.v(TAG, "doInBackground() pdfFile invoked " + pdfFile.getAbsoluteFile());
try {
pdfFile.createNewFile();
Log.v(TAG, "doInBackground() file created" + pdfFile);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "doInBackground() error" + e.getMessage());
Log.e(TAG, "doInBackground() error" + e.getStackTrace());
}
FileDownloader.downloadFile(fileUrl, pdfFile);
Log.v(TAG, "doInBackground() file download completed");
return null;
}
}

First of all, WRITE permission grants you both READ/WRITE access, so you don't need to send a request for both
Check if permission is granted by this method, no need for all of those API checks:
private boolean isPermissionGranted(String permission) {
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
If permission is not granted first before everything else just request the permission:
requestPermissions(new String[Manifest.permission.WRITE_EXTERNAL_STORAGE], 123);
Check if permission is granted and then continue your work:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 123 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Do your work
}
else {
//Permission is not granted do what you want
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
In your code:
inside holder.pdf.setOnClickListener()'s onCLick()
if (!isPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
requestPermissions(new String[Manifest.permission.WRITE_EXTERNAL_STORAGE], 123);
} else {
//Do your job
}

Related

How to access hidden files in android 11 programmatically?

I want to show whatsapp statuses in my app.
Till now I have done following:
public final String getStatusPath(boolean z) {
if (Build.VERSION.SDK_INT < 30) {
if (z) {
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp Business/Media/.Statuses";
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp/Media/.Statuses";
} else if (z) {
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp.w4b/WhatsApp Business/Media/.Statuses";
} else {
return Environment.getExternalStorageDirectory().getAbsolutePath()+ "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses";
}
}
private ArrayList<WhatStatusData> getStatusList() {
ArrayList<WhatStatusData> arrayList = new ArrayList<>();
File[] listFiles = new File(FileConstants.INSTANCE.getStatusPath(isBusiness)).listFiles();
int i = 0;
if (listFiles != null) {
if (listFiles.length == 0) {
Arrays.sort(listFiles);
}
int length = listFiles.length;
while (i < length) {
File file = listFiles[i];
i++;
String absolutePath = file.getAbsolutePath();
Uri fromFile = Uri.fromFile(file);
String name = file.getName();
if (!name.equals(".nomedia")) {
arrayList.add(new WhatStatusData(absolutePath, fromFile, name));
}
}
}
return arrayList;
}
In manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
But I am not getting data in android 11.In other versions code is working properly.
Got the solution
There are two possibility for getting hidden files access in android 11
give MANAGE_EXTERNAL_STORAGE permission as said by #Subarata Talukder
give particular folder access permission using storage manager as explained below (without using MANAGE_EXTERNAL_STORAGE permission)
Here I am showing how to access whatsapp statuses programmatically
//give permissions in manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
//give run time permissions
static final int REQUEST_PERMISSION_KEY = 1;
int REQUEST_ACTION_OPEN_DOCUMENT_TREE = 101;
SharedPreferences sharedPreferences;
check if run time permissions are given or not on button click
if(sharedPreferences.getString("WATREE","").equals("")){
if(checkAndRequestPermissions()){
if (SDK_INT >= Build.VERSION_CODES.Q) {
askPermission();
}else {
callActivity();
}
}
}else{
callActivity();
}
private boolean checkAndRequestPermissions() {
int writePerm = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
int readPerm = ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.READ_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (writePerm != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if(readPerm != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(GBV_StartActivity.this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
REQUEST_PERMISSION_KEY);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_KEY) {
try {
Map<String, Integer> permsLogin = new HashMap<>();
// Initialize the map with both permissions
permsLogin.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
permsLogin.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
permsLogin.put(permissions[i], grantResults[i]);
// Check for both permissions
if (permsLogin.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& permsLogin.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
if (SDK_INT >= Build.VERSION_CODES.Q) {
askPermission();
}else {
callActivity();
}
// process the normal flow
//else any one or both the permissions are not granted
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialogOK((dialog, which) -> {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
break;
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(getApplicationContext(), "Go to settings and enable permissions.", Toast.LENGTH_LONG)
.show();
finish();
//proceed with logic by disabling the related features or quit the app.
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void showDialogOK(DialogInterface.OnClickListener okListener) {
android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(GBV_StartActivity.this);
alertDialogBuilder.setMessage("You need to allow access to the permissions.")
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener);
android.app.AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
public void callActivity(){
startActivity(new Intent(GBV_StartActivity.this, MainActivity.class));
}
private String getWhatsupFolder() {
String oldPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp/Media/.Statuses";
String oldBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp Business/Media/.Statuses";
String newPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses";
String newBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp.w4b/WhatsApp Business/Media/.Statuses";
String finalPath;
if(new File(newBusinessPath).exists()){
finalPath = "Android%2Fmedia%2Fcom.whatsapp.w4b%2FWhatsApp Business%2FMedia%2F.Statuses";
}else if(new File(newPath).exists()){
finalPath = "Android%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia%2F.Statuses";
}else if(new File(oldBusinessPath).exists()){
finalPath = "WhatsApp Business%2FMedia%2F.Statuses";
}else {
finalPath = "WhatsApp%2FMedia%2F.Statuses";
}
return finalPath;
}
#RequiresApi(Build.VERSION_CODES.Q)
private void askPermission() {
StorageManager storageManager = (StorageManager) getSystemService(STORAGE_SERVICE);
Intent intent = storageManager.getPrimaryStorageVolume().createOpenDocumentTreeIntent();
String targetDirectory = getWhatsupFolder(); // add your directory to be selected by the user
Uri uri = intent.getParcelableExtra("android.provider.extra.INITIAL_URI");
String scheme = uri.toString();
scheme = scheme.replace("/root/", "/document/");
scheme += "%3A"+targetDirectory;
uri = Uri.parse(scheme);
Log.w("TAG", "askPermission: uri::"+uri );
intent.putExtra("android.provider.extra.INITIAL_URI", uri);
startActivityForResult(intent, REQUEST_ACTION_OPEN_DOCUMENT_TREE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == this.REQUEST_ACTION_OPEN_DOCUMENT_TREE && resultCode == -1) {
Uri data = intent.getData();
try {
getContentResolver().takePersistableUriPermission(data, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} catch (Exception e) {
e.printStackTrace();
}
SharedPreferences.Editor editor2 = sharedPreferences.edit();
editor2.putString("WATREE", data.toString());
editor2.apply();
callActivity();
}
}
now after giving all permissions try to get images or videos from storage like below:
if (SDK_INT >= Build.VERSION_CODES.Q) {
DocumentFile[] allFiles = getFromSdcard();
if (allFiles != null) {
for(int i = 0 ; i <allFiles.length ; i++){
if (!allFiles[i].getUri().toString().contains(".nomedia")) {
Log.e("path:",allFiles[i].getUri().toString());
//add data in your arraylist
}
}
}
}else {
String oldPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp/Media/.Statuses";
String oldBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp Business/Media/.Statuses";
String newPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses";
String newBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp.w4b/WhatsApp Business/Media/.Statuses";
String finalPath;
if (!new File(oldPath).exists()) {
if (!new File(oldBusinessPath).exists()) {
if (!new File(newPath).exists()) {
if (!new File(newBusinessPath).exists()) {
finalPath = oldPath;
} else {
finalPath = newBusinessPath;
}
} else {
finalPath = newPath;
}
} else {
finalPath = oldBusinessPath;
}
} else {
finalPath = oldPath;
}
File file2 = new File(finalPath);
if (file2.exists()) {
File[] listFiles = file2.listFiles();
if (listFiles != null) {
for (int i = 0; i < listFiles.length; i++) {
Log.e("path:",listFiles[i].getPath()+"");
//add data in your arraylist
}
}
}
}
public DocumentFile[] getFromSdcard() {
DocumentFile fromTreeUri = DocumentFile.fromTreeUri(getContext(), Uri.parse(sharedPreferences.getString("WATREE","")));
if (fromTreeUri == null || !fromTreeUri.exists() || !fromTreeUri.isDirectory() || !fromTreeUri.canRead() || !fromTreeUri.canWrite()) {
return null;
}
return fromTreeUri.listFiles();
}

Android 11 Download File to Download Folder doesn't work

currently I'm trying to download a File with the DownloadManager but that doesn't work, the download starts but there is no File inside the Download Folder after downloading.
Thats my Code:
private void downloadAddon() {
try{
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setTitle("download");
request.setDescription("apk downloading");
// request.setAllowedOverRoaming(false);
request.setDestinationUri(Uri.fromFile(new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) , "mod.mcpack")));
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
long downloadID = downloadManager.enqueue(request);
//Just for testing
if (downloadComplete(downloadID)) {
Toast.makeText(this, "Download Status: Completed", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Download Status: Error", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
//Not required, there is no error that crashes the app
Toast.makeText(this, "Error catched: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private boolean downloadComplete(long downloadId){
DownloadManager dMgr = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Cursor c= dMgr.query(new DownloadManager.Query().setFilterById(downloadId));
if(c.moveToFirst()){
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if(status == DownloadManager.STATUS_SUCCESSFUL){
return true; //Download completed, celebrate
}else{
int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
Log.d(getPackageName(), "Download not correct, status [" + status + "] reason [" + reason + "]");
return false;
}
}
return false;
}
The Log says: Download not correct, status [1] reason [0]
Did something changed since Android 11 except the new storage rules?
I found an solution on Stackoverflow (Can't find the link anymore)
private boolean downloadTask(String url) throws Exception {
if (!url.startsWith("http")) {
return false;
}
String name = "temp.mcaddon";
try {
File file = new File(Environment.getExternalStorageDirectory(), "Download");
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.mkdirs();
}
File result = new File(file.getAbsolutePath() + File.separator + name);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setDestinationUri(Uri.fromFile(result));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (downloadManager != null) {
downloadManager.enqueue(request);
}
//mToast(mContext, "Starting download...");
MediaScannerConnection.scanFile(DetailsActivity.this, new String[]{result.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
Log.e(">>>>>", e.toString());
//mToast(this, e.toString());
return false;
}
return true;
}
This should work for Android 11
Use this Function it save File in Download folder :
private boolean downloadTask(String url , String name) throws Exception {
try {
File file = new File(Environment.getExternalStorageDirectory(), "Download");
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.mkdirs();
}
File result = new File(file.getAbsolutePath() + File.separator + name);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setDestinationUri(Uri.fromFile(result));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setAllowedOverRoaming(false).setTitle(name);//for mp3 title
request.setDescription("Something useful. No, really.");
if (downloadManager != null) {
downloadManager.enqueue(request);
}
//mToast(mContext, "Starting download...");
MediaScannerConnection.scanFile(MainActivity.this, new String[]{result.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("tag >>>>", "on Downlaod check it");
}
});
} catch (Exception e) {
Log.i("tag >>>> ", e.toString());
return false;
}
return true;
}
But in Manifest add some lines.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"
>
Add this line in OnCreate :
//check permission
if (Build.VERSION.SDK_INT >= 23) {
Log.i("log ", "if in Build.VERSION.SDK_INT>=23");
checkper(); //<-- this is a function
} else {
Log.i("log ", " else else in Build.VERSION.SDK_INT>=23");
}
This is checkper() Function:
private final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
private void checkper() {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
} else {
Log.i("log", "else in checkper()");
//your code
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED
&& grantResults[2] == PackageManager.PERMISSION_GRANTED
&& grantResults[3] == PackageManager.PERMISSION_GRANTED) {
Log.i("log", "if in onRequestPermissionsResult()");
//dar seri aval har do ra dasti ok kardim amad inja
//your code
} else {
Log.i("log", "else in onRequestPermissionsResult()");
// yeki taiiid kardi
}
}
}//switch
}//onRequestPermissionsResult

Not able to upload image from camera and gallery in Android 8 & 9

I have a profile picture concept in my app. User has options to upload an image from camera or gallery in the app but the problem is the image is being uploaded to some devices not all. Mainly the problem occurs with Android version 8 & 9. I tried almost everything but failed to achieve. Please help.
Code:
dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_image_upload);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
TextView txtTakePhoto = (TextView) dialog.findViewById(R.id.txtTakePhoto);
TextView txtPictureFromGallery = (TextView) dialog.findViewById(R.id.txtPictureFromGallery);
ImageView imgClose = (ImageView) dialog.findViewById(R.id.imgClose);
imgClose.setOnClickListener(this);
txtTakePhoto.setOnClickListener(this);
txtPictureFromGallery.setOnClickListener(this)
Code for take photo from camera:
case R.id.txtTakePhoto:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
{
cameraIntent();
}
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, PHONE_PERMISSION_CODE);
}
} else {
cameraIntent();
}
break;
Code for take photo from gallery:
case R.id.txtPictureFromGallery:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
{
imageBrowse();
}
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PHONE_PERMISSION_CODE);
}
} else {
imageBrowse();
}
break;
Pending code for image uploading :
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_REQUEST) {
onSelectFromGalleryResult(data);
} else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult(data);
}
}
//
if (requestCode == 2 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri DbsUri = data.getData();
fileDbs = FilePath.getPath(getActivity(), DbsUri);
File f1 = new File(fileDbs);
edtCertificatesValue.setText(f1.getName());
Log.e("tag", "filedbs" + fileDbs);
} else if (requestCode == 3 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri picUri = data.getData();
filePath = FilePath.getPath(getActivity(), picUri);
File f2 = new File(filePath);
edtIdentityDocumentValue.setText(f2.getName());
Log.e("tag", "filePath" + filePath + " " + f2.getName());
} else if (requestCode == 4 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri picUri = data.getData();
fileAddress = FilePath.getPath(getActivity(), picUri);
File f3 = new File(fileAddress);
edtProofOfAddressValue.setText(f3.getName());
Log.e("tag", "fileAddress" + fileAddress);
} else if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri CvUri = data.getData();
fileCvPath = FilePath.getPath(getActivity(), CvUri);
File f4 = new File(fileCvPath);
edtCurriculumVitaeValue.setText(f4.getName());
Log.e("tag", "fileCvPath" + fileCvPath);
//
}
//
// } else
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
bm = null;
File imageFile = getTempFile(getActivity());
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
boolean isCamera = (data == null ||
data.getData() == null ||
data.getData().toString().contains(imageFile.toString()));
if (isCamera) { /* CAMERA */
selectedImageUri = Uri.fromFile(imageFile);
} else { /* ALBUM */
selectedImageUri = data.getData();
}
bm = getImageResized(getActivity(), selectedImageUri);
int rotation = getRotation(getActivity(), selectedImageUri, isCamera);
bm = rotate(bm, rotation);
ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 99, bytes1);
byte[] byteImage = bytes1.toByteArray();
encodeImage = Base64.encodeToString(byteImage, Base64.DEFAULT);
imgProfile.setImageBitmap(bm);
Uri picUri = data.getData();
Log.e("TAG", "onSelectFromGalleryResult: " + bm);
fileImagePath = getPath(picUri);
if (fileImagePath != null) {
try {
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
private String getPath(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getActivity(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
// new code
private static File getTempFile(Context context) {
File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 99, bytes1);
byte[] byteImage = bytes1.toByteArray();
encodeImage = Base64.encodeToString(byteImage, Base64.DEFAULT);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
Log.d("TAG", "onActivityResult: " + Uri.fromFile(destination));
try {
rotateImageIfRequired(thumbnail, getActivity(), Uri.fromFile(destination));
} catch (Exception e) {
e.printStackTrace();
}
Log.d("TAG", "thumbnail: " + thumbnail);
imgProfile.setImageBitmap(thumbnail);
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes1.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fileImagePath = destination.toString();
if (fileImagePath != null) {
try {
// execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.some_error_occured), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(getActivity(), "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(getActivity(), "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
API hit Code:
private void execMultipartPost() throws Exception {
RequestBody requestBody;
pBar.setVisibility(View.VISIBLE);
final HashMap<String, String> loggedDetail = sessionManager.getLoggedDetail();
HashMap<String, String> params = new HashMap<String, String>();
String api_token = loggedDetail.get("api_token");
if (filePath != null) {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
fileBody = RequestBody.create(MediaType.parse(contentType), file);
filename = "file_" + System.currentTimeMillis() / 1000L;
Log.e("TAG", "filename: " + filename);
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_file", filename + ".jpg", fileBody)
.addFormDataPart("name", edtName.getText().toString())
.addFormDataPart("user_id", loggedDetail.get("id"))
.addFormDataPart("email", edtEmailValue.getText().toString())
.addFormDataPart("postal_code", edtPostCodeValue.getText().toString())
.addFormDataPart("phone", edtPhoneNumber.getText().toString())
.addFormDataPart("type", loggedDetail.get("type"))
.addFormDataPart("address", edtAddressValue.getText().toString())
.addFormDataPart("gender", edtGenderValue.getText().toString())
.addFormDataPart("skype_id", edtSkypeNameIdValue.getText().toString())
.build();
} else {
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_file", "")
.addFormDataPart("name", edtName.getText().toString())
.addFormDataPart("user_id", loggedDetail.get("id"))
.addFormDataPart("email", edtEmailValue.getText().toString())
.addFormDataPart("postal_code", edtPostCodeValue.getText().toString())
.addFormDataPart("phone", edtPhoneNumber.getText().toString())
.addFormDataPart("type", loggedDetail.get("type"))
.addFormDataPart("address", edtAddressValue.getText().toString())
.addFormDataPart("gender", edtGenderValue.getText().toString())
.addFormDataPart("skype_id", edtSkypeNameIdValue.getText().toString())
.build();
}
okhttp3.Request request = new okhttp3.Request.Builder()
.url(Constants.EDIT_PROFILE_DATA)
.post(requestBody)
.addHeader("Authorization", "Bearer " + loggedDetail.get("api_token"))
.build();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(150, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
pBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Yes, you need to configure the FileProvider. In your app's manifest, add a provider to your application:
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
...
</application>
Make sure that the authorities string matches the second argument to getUriForFile(Context, String, File). In the meta-data section of the provider definition, you can see that the provider expects eligible paths to be configured in a dedicated resource file, res/xml/file_paths.xml. Here is the content required for this particular example:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
Read the android documentation https://developer.android.com/training/camera/photobasics

Getting no image with error message while using camera to take photo in android

I have implemented Camera and Gallery option to Take picture and choose from gallery accordingly in my app. After running the app, when I click camera option at first it takes permission from me.Now while taking a photo, the imageview become blank by giving error message that E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException. But when I go to gallery option, and choose photo and it shows into imageview. Now if I go to camera option now, I can take photo and see in imageview. The problem is, if i click camera option at first, it does not work, but if i click it after gallery option it works.
My Code for taking pictire and picking up gallery image is
public class ViewProfileFragment extends Fragment implements View.OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_view_profile, container, false);
image=(ImageView)rootView.findViewById(R.id.profile_pic);
saveData();
return rootView;
}
public void saveData(){
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
String mImageUri = preferences.getString("image", null);
if (mImageUri != null) {
image.setImageURI(Uri.parse(mImageUri));
System.out.println("imageuri"+Uri.parse(mImageUri));
} else {
Glide.with( this )
.load(Constants.HTTP.PHOTO_URL+mail)
.thumbnail(0.5f)
.override(200,200)
.diskCacheStrategy( DiskCacheStrategy.ALL)
.into( image);
}
}
.....
public void showDialog(){
//Create a new builder and get the layout.
....
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListViekw Clicked item index
if (position == 0) {
userChoosenTask ="Take Photo";
alert.dismiss();
if(isPermissionGrantedCamera()&&isPermissionGrantedCameraWrite()) {
cameraIntent();
}
}
else if (position == 1){
userChoosenTask ="Choose from Library";
alert.dismiss();
if(isPermissionGrantedGallery()) {
galleryIntent();
}
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode==CODE_GALLERY_REQUEST){
if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
galleryIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
if(requestCode==MY_CAMERA_REQUEST_CODE){
if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
cameraIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
super.onRequestPermissionsResult( requestCode, permissions, grantResults );
}
......
public boolean isPermissionGrantedGallery() {
if (Build.VERSION.SDK_INT >= 23) {
if (getActivity().checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG","Permission is granted");
return true;
}
}
public boolean isPermissionGrantedCamera() {
if (Build.VERSION.SDK_INT >= 23) {
if (getActivity().checkSelfPermission(android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED){
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.CAMERA}, 0);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG","Permission is granted");
return true;
}
}
public boolean isPermissionGrantedCameraWrite() {
if (Build.VERSION.SDK_INT >= 23) {
if (getActivity().checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED){
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG","Permission is granted");
return true;
}
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
public void cameraIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File cameraFolder;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cameraFolder = new File(Environment.getExternalStorageDirectory(), "image/");
} else {
cameraFolder = getActivity().getCacheDir();
}
if (!cameraFolder.exists()) {
cameraFolder.mkdirs();
}
String imageFileName = System.currentTimeMillis() + ".jpg";
File photoFile = new File(cameraFolder + imageFileName);
currentPhotoPath = photoFile.getAbsolutePath();
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_CAMERA);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE && data!=null){
onSelectFromGalleryResult(data);
}
else if (requestCode == REQUEST_CAMERA ) {
if(!TextUtils.isEmpty(currentPhotoPath)) {
try {
galleryAddPic();
onCaptureImageResult();
}
catch (Exception e){
}
}
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
uri = Uri.fromFile(f);
mediaScanIntent.setData(uri);
this.getActivity().sendBroadcast(mediaScanIntent);
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(uri));
editor.commit();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
private void onCaptureImageResult() {
Bitmap bitmap = getBitmapFromPath(currentPhotoPath, 200, 200);
image.setImageBitmap(bitmap);
compressBitMap(bitmap);
}
private void onSelectFromGalleryResult(Intent data) {
uri = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
currentPhotoPath = cursor.getString(column_index);
uri = Uri.fromFile(new File(currentPhotoPath));
cursor.close();
} else {
currentPhotoPath = uri.getPath();
}
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(uri));
editor.commit();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
bm = BitmapFactory.decodeFile(currentPhotoPath);
compressBitMap(bm);
}
private void compressBitMap(Bitmap bitmap) {
ImageConversion imageConversion = new ImageConversion();
byte[] bytesArray;
int maxSize = 10 * 1024;
int imageMaxQuality = 50;
int imageMinQuality = 5;
bytesArray = imageConversion.convertBitmapToByteArray(bitmap, imageMaxQuality, imageMinQuality, maxSize);
File destination = new File(getContext().getApplicationContext().getFilesDir(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytesArray);
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
currentPhotoPath = destination.getPath();
uploadImage(bytesArray);
}
public static Bitmap getBitmapFromPath(String photoPath, int targetW, int targetH) {
.....
}
//This code i sfor photo uploading
private void uploadImage(final byte[] bytesArray){
trustAllCertificates();
StringRequest stringRequest = new StringRequest( Request.Method.POST, UPLOAD_URL+mail,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d( "Error Response"," "+response );
if(response.contains( "!DOCTYPE" )){
.....
}
else{
Toast.makeText(getActivity(), "Photo is uploaded successfully", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Showing toast
Toast.makeText(getActivity(),"Server is not connected. Please check your internet connection" /*volleyError.getMessage().toString()*/, Toast.LENGTH_LONG).show();
Log.d( "Volley Error"," "+volleyError );
}
}){
#Override public byte[] getBody() {
return bytesArray;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put( "Content-Type", "image/jpeg" );
headers.put( "Accept","*/*");
Log.d( "headers", String.valueOf( headers ) );
return headers;
}
};
RequestQueue requestQueue = Application.get().getRequestQueue();
requestQueue.add(stringRequest);
}
}
And Manifest is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.and">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
.....
</manifest>
The Error Message
09-25 08:59:30.351 5093-5093/demo.app.com.bluapp_client_and E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/image1506329962799.jpg (Permission denied)
09-25 08:59:30.352 5093-5093/demo.app.com.bluapp_client_and E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/image1506329962799.jpg (Permission denied)

ActivityCompat.requestPermissions Doesn't Show Dialog in Android

Android Version on Phone : 6.0.1 ( Android marshmallow )
Android target SDK Version 25
I Calling the ActivityCompat.requestPermissions in Android button but doesn't show dialog to Procced it
Button
printrequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try{
verifyStoragePermissions(SickFragmentId.this);
}
catch(Exception e ){
Log.e("LoginActv: Save Block", e.getMessage());
e.getStackTrace();
}
String req = textViewReqNo.getText().toString();
String name = Name.getText().toString();
String branch = Branch.getText().toString();
String departement_position = Departement_Position.getText().toString();
String status = Status.getText().toString();
String description = Description.getText().toString();
String type = Status.getText().toString();
String date = Date.getText().toString();
Intent showId = new Intent(SickFragmentId.this, print.class);
startActivity(showId);
}
});
And i put the code in Print.java
public class print extends Activity {
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
Log.e("Permission value", permission + " ");
if (permission != 1) {
Log.e("Permission ask", "Asking, permission not granted");
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 200) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("PERResult", "Granted");
String FILE = Environment.getExternalStorageDirectory().toString()
+ "/PDF/" + "AldanRIZKISANTOSA.pdf";
Document document = new Document(PageSize.A4);
// Create Directory in External Storage
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/PDF");
myDir.mkdirs();
// Create Pdf Writer for Writting into New Created Document
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
// Open Document for Writting into document
document.open();
// User Define Method
addMetaData(document);
addTitlePage(document);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Close Document after writting all content
document.close();
Toast.makeText(this, "PDF File is Created. Location : " + FILE,
Toast.LENGTH_LONG).show();
} else {
Log.e("PERResult", "Denied");
Toast.makeText(getApplicationContext(), "PERMISSION_DENIED", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
// Set PDF document Properties
public void addMetaData(Document document)
{
document.addTitle("RESUME");
document.addSubject("Person Info");
document.addKeywords("Personal, Education, Skills");
document.addAuthor("TAG");
document.addCreator("TAG");
}
public void addTitlePage(Document document) throws DocumentException {
// Font Style for Document
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
| Font.UNDERLINE, BaseColor.GRAY);
Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL);
// Start New Paragraph
Paragraph prHead = new Paragraph();
// Set Font in this Paragraph
prHead.setFont(titleFont);
// Add item into Paragraph
prHead.add("RESUME – Name\n");
// Create Table into Document with 1 Row
PdfPTable myTable = new PdfPTable(1);
// 100.0f mean width of table is same as Document size
myTable.setWidthPercentage(100.0f);
// Create New Cell into Table
PdfPCell myCell = new PdfPCell(new Paragraph(""));
myCell.setBorder(Rectangle.BOTTOM);
// Add Cell into Table
myTable.addCell(myCell);
prHead.setFont(catFont);
prHead.add("\nName1 Name2\n");
prHead.setAlignment(Element.ALIGN_CENTER);
// Add all above details into Document
document.add(prHead);
document.add(myTable);
document.add(myTable);
// Now Start another New Paragraph
Paragraph prPersinalInfo = new Paragraph();
prPersinalInfo.setFont(smallBold);
prPersinalInfo.add("Address 1\n");
prPersinalInfo.add("Address 2\n");
prPersinalInfo.add("City: SanFran. State: CA\n");
prPersinalInfo.add("Country: USA Zip Code: 000001\n");
prPersinalInfo
.add("Mobile: 9999999999 Fax: 1111111 Email: john_pit#gmail.com \n");
prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
document.add(prPersinalInfo);
document.add(myTable);
document.add(myTable);
Paragraph prProfile = new Paragraph();
prProfile.setFont(smallBold);
prProfile.add("\n \n Profile : \n ");
prProfile.setFont(normal);
prProfile
.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
prProfile.setFont(smallBold);
document.add(prProfile);
// Create new Page in PDF
document.newPage();
}
}
But the Dialog for permission doesn't show
Before i use ActivityCompat.requestPermissions i have error
java.io.FileNotFoundException: /storage/emulated/0/PDF/Name.pdf (Permission denied)
After i use ActivityCompat.requestPermission i have error
E/Permission value: -1
E/Permission ask: Asking, permission not granted
if( hasPermissionWriteExternalStorage()){
//do smth
}
public boolean hasPermissionWriteExternalStorage() {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_STORAGE);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {case PERMISSION_WRITE_EXTERNAL_STORAGE: {
if (getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//do smth
} else {
Toast.makeText(getActivity(), "Access Denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
in onCreate() method;
requestStoragePermission();
and define this method;
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.GET_ACCOUNTS)) {
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_CONTACTS)) {
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.CAMERA)) {
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_PHONE_STATE)) {
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]
{
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.GET_ACCOUNTS,
android.Manifest.permission.READ_CONTACTS,
android.Manifest.permission.CAMERA,
android.Manifest.permission.READ_PHONE_STATE
}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}

Categories

Resources