android6.0 can't get gallery path , I have got uses-permission - android

I want to get photo from my photo gallery to crop it, but the path is null. Andorid5.0 can use this way, but Android 6.0 and Android 7.0 can't use this way. I have got this app permission.
public void initPop(View view) {
albums = (TextView)view.findViewById(R.id.albums);
cancel = (LinearLayout) view.findViewById(R.id.cancel);
albums.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popupWindow.dismiss();
Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(openAlbumIntent, PHOTOZOOM);
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popupWindow.dismiss();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
Uri uri = null;
switch (requestCode) {
case PHOTOZOOM:
if (data == null) {
return;
}
uri = data.getData();
String[] proj = {
MediaStore.Images.Media.DATA
};
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
Log.i("Ienning", "onActivityResult: the cursor is " + column_index);
path = cursor.getString(column_index);
}
Intent intent3 = new Intent(PersonCenter.this, ClipActivity.class);
intent3.putExtra("path", path);
Log.i("Ienning", "The Path is " + path);
startActivityForResult(intent3, IMAGE_COMPLETE);
break;
case IMAGE_COMPLETE:
final String temppath = data.getStringExtra("path");
editor.putString("temppath", temppath);
editor.commit();
head.setImageBitmap(getLoacalBitmap(temppath));
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
And permission code:
public void getpermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))
{
new AlertDialog.Builder(this)
.setMessage("get permission")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(PersonCenter.this, new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
}
}).show();
} else {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
}
}
else {
Log.i("Ienning", " this is ok manifest permission");
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_STORAGE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("Ienning", "onRequestPermissionResult: the result permission is ok!");
} else {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "permission denied!", Toast.LENGTH_SHORT).show();
}
}
return;
}
}
And loginfo is
10-28 19:39:44.424 25265-25265/com.example.ienning.ncuhome I/Ienning: onActivityResult: the cursor is 0
10-28 19:39:44.425 25265-25265/com.example.ienning.ncuhome I/Ienning: The Path is null

Andorid5.0 can use this way
You did not test it very well. Your approach will fail on all Android devices, at least some of the time. It will fail more frequently on Android 6.0+.
Your code makes two invalid assumptions:
You assume that the Uri that comes back from ACTION_GET_CONTENT has something to do with the MediaStore. This is incorrect. The Uri that comes back from ACTION_GET_CONTENT can be anything that the user-selected activity wants to return. All that is more-or-less guaranteed is that you can use ContentResolver and openInputStream() to read the content.
You assume that the MediaStore will always give you a DATA column that is usable. That is not a requirement, even if the MediaStore happens to know about the Uri (see the previous bullet).
If the scheme of the Uri that you get back from ACTION_GET_CONTENT is file, then getPath() will be a filesystem path. You may be able to use that path (otherwise, it is a bug in the third-party app that gave you that Uri).
More commonly, the scheme of the Uri will be content. In that case, you can use ContentResolver and openInputStream() to read in the content identified by that Uri, but there is no required filesystem path behind that Uri. That Uri can point to anything the other developer wants: BLOB columns in databases, files in locations that you cannot access, data that needs to be downloaded because it is not yet on the device, etc.

Related

Get the user selected file's name and path irrespective of its location [ either in internal or external memory ] in Android?

Instead of the hard coded storage location in the code below, I would like to get the [name & path] of any Excelsheet that user selects, for data import operation. Found that getExternalStorageDirectory is deprecated, not sure how to achieve the requirement for accessing Excelfile from both Internal / External storage of Android.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case imrequestcode:
// Need help at this LOC where filepath could be user selected one.
String FilePath = "/mnt/sdcard/" + "sampleinput.xls";
try {
if (resultCode == RESULT_OK) {
//// Import function goes here
}
} catch (Exception ex) {
lbl.setText("Error " + e);
}
break;
}
}
Intent : Pick an excel sheet which has inputdata
bimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
fileintent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_LOCATION_ACCESS);
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_READ_EXTERNAL_STORAGE);
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
fileintent.setType("application/vnd.ms-excel");
try {
startActivityForResult(fileintent, importrequestcode);
fileintent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT > 22) {
requestPermissions(new String[]{"FLAG_GRANT_READ_URI_PERMISSION"}, 11);
}
} catch (ActivityNotFoundException e) {
lbl.setText("No file picker activity.");
}
}
});
}
To get the Filename:
private String getFileName(Uri uri) {
Cursor mCursor =
getApplicationContext().getContentResolver().query(uri, null, null, null, null);
int indexedname = mCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
mCursor.moveToFirst();
String filename = mCursor.getString(indexedname);
mCursor.close();
return filename;
}
To get the FilePath:
[Checkthislink](https://stackoverflow.com/questions/13209494/how-to-get-the-full-file-path-from-uri/55469368#55469368)
Call the method and class in onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case imrequestcode:
Uri fileuri = data.getData();
String Nameoffile_selected = getFileName(fileuri);
String Pathoffile_selected = FileUtils.getPath(this, fileuri);
try {
if (resultCode == RESULT_OK) {
//// Import function goes here
}
} catch (Exception ex) {
lbl.setText("Error " + e);
}
break;
}
}

How to delete SDcard file in Android

I tried to delete the image file from the gallery, but it won't. Image files are output normally, and sharing functions are done. It can't write and delete in my App. Files are deleted from the default app.
I tried to delete it use File class and ContentResolver. but file has not been deleted.
Android targetSdkVersion is 26 and compileSdkVersion is 28.
Manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I get SDcard path from getSDcardPath()
public String getSDcardPath(Context context) {
File[] storage = ContextCompat.getExternalFileDirs(context, null);
if(storage.length > 1 && storage[0] != null && storage[1] != null)
return storage[1].toString();
else
return "";
}
File Class code Used
public void useFileClass() {
File mFile = new File("file Parent + file NAME");
if (mFile.exists()) {
mFile.delete();
}
}
ContentResolver code Used
public void useContentResolver(Context context, File mFile) {
ContentResolver contentResolver = context.getContentResolver();
Uri mUri = getUri(context, mFile);
contentResolver.delete(mUri, null, null);
}
public Uri getUri(Context context, File mFile) {
Uri mUri;
mUri = FileProvider.getUriForFile(context, "MyApplication", mFile);
return mUri;
}
share code
public void shareImage() {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, getUri(this, mFile));
startActivity(Intent.createChooser(shareIntent, "Share image too..."));
}
You need request Permission before access into storage. Try this:
private static final int MY_WRITE_STORAGE_PERMISSION_CODE = 200;
private void checkPermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_WRITE_STORAGE_PERMISSION_CODE);
} else {
// Todo (Add, Delete, Edit, ...)
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == MY_WRITE_STORAGE_PERMISSION_CODE)
{
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
// Todo (Add, Delete, Edit, ...)
} else {
// Permission Deny
}
}
}
Hope this help you.

Android - how to capture selected video by intent

I'm writting a code that the user can upload video from his phone.
My only problem is that i dont know how to get/save the file.
With the intent the user access to his libary and choose his video.
But then i dont know how to get what he choose
Here is my code
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btnVideo.setOnClickListener(this);
btnAudio.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.btnUploadVideo:
if(!checkStoragePermission())return;
uploadVideo();
break;
case R.id.btnUploadAudio:
break;
}
}
private void uploadVideo() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Video"),OPEN_MEDIA_PICKER);
}
private boolean checkStoragePermission(){
int resultCode = ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
boolean granted = resultCode == PackageManager.PERMISSION_GRANTED;
if (!granted){
ActivityCompat.requestPermissions(
getActivity(),
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
PICK_VIDEO_REQUEST /*Constant Field int*/
);
}
return granted;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PICK_VIDEO_REQUEST && grantResults[0] == PackageManager.PERMISSION_GRANTED){
uploadVideo();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == PICK_VIDEO_REQUEST) {
Uri selectedImageUri = data.getData();
}
}
}
What should i do on the "onActivityResult"? How should i save/get the user choose.
My only problem is that i dont know how to get/save the file.
Your code has nothing to do with a file.
If you want the use to pick a file, use a third-party file-chooser library.
Your code is having the user choose a piece of content, and that content does not have to be a file, let alone a file that you have direct filesystem access to.
You are welcome to use data.getData() to get the Uri to the content, then use ContentResolver and openInputStream() to get an InputStream on that content, if that meets your needs.

Problems with accessing camera with targetSdkVersion 25?

I have an app that uses camera it works fine when I compile it with targetSdkVersion 23, but when I try to use version 25 I get this error:
android.os.FileUriExposedException:
file:///storage/emulated/0/DCIM/IMG_1093948364.jpg exposed beyond app
through ClipData.Item.getUri()
This is the code that I'm using:
private void showCameraAction() {
if(ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
getString(R.string.mis_permission_rationale_write_storage),
REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
}else {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
try {
mTmpFile = FileUtils.createTmpFile(getActivity());
} catch (IOException e) {
e.printStackTrace();
}
if (mTmpFile != null && mTmpFile.exists()) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
startActivityForResult(intent, REQUEST_CAMERA);
} else {
Toast.makeText(getActivity(), R.string.mis_error_image_not_exist, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(), R.string.mis_msg_no_camera, Toast.LENGTH_SHORT).show();
}
}
}
private void requestPermission(final String permission, String rationale, final int requestCode){
if(shouldShowRequestPermissionRationale(permission)){
new AlertDialog.Builder(getContext())
.setTitle(R.string.mis_permission_dialog_title)
.setMessage(rationale)
.setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{permission}, requestCode);
}
})
.setNegativeButton(R.string.mis_permission_dialog_cancel, null)
.create().show();
}else{
requestPermissions(new String[]{permission}, requestCode);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_STORAGE_WRITE_ACCESS_PERMISSION){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
showCameraAction();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
What should I do? Thanks.
Your FileUtils.createTmpFile(getActivity()); probably uses file:// URI to share file with other app(in your case camera).
Android versions greater then 24 use content:// URIs instead, and will throw this exception when you try to share a file directly using the file:// URI.
A content URI allows you to grant read and write access using temporary access permissions
Take a look at FileProvider.
SOLUTION:
Changed this:
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
To this:
//getActivity() because its a fragment
Uri uri = FileProvider.getUriForFile(getActivity(),
getActivity().getPackageName()
, mTmpFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
And it worked.

How to get image from gallery in android marshmallow?

Hi i am working in app were user can select image when he is registering an account. I am able to get image on lollipop but when i am testing it in marshmallow then i am not getting file and its name, I am able to ask permission from user and when i am selecting image from gallery i am not getting any file or its name
This is my Code
select_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >=23) {
if (checkPermission()){
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}else{
requestPermission();
}
}else{
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
}
});
My Permissions
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(Register.this, Manifest.permission.READ_EXTERNAL_STORAGE );
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(Register.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(Register.this, "Write External Storage permission allows us to access images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(Register.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
if(requestCode == PERMISSION_REQUEST_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Accepted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
}
}
After Selecting Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
img_name.setText(file_name);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I am not getting why its not working in marshmallow even i have given permissions
I solved it.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
img_name.setText(file_name);
}
}
}else {
String path= data.getData().getPath();
file_name=path.substring(path.lastIndexOf("/")+1);
img_name.setText(file_name);
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
When i was selecting file , then i was not going to this condition
if (filePath.getScheme().equals("content"))
so in else condition i have given this
String path= data.getData().getPath();
file_name=path.substring(path.lastIndexOf("/")+1);
img_name.setText(file_name);
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
To get image from gallery on any api level then follow this :
Copy and paste all 4 function to your activity
And call this to open gallery galleryPermissionDialog();
Variable used
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
protected static final int REQUEST_CODE_MANUAL = 5;
Permission need to add for lower than marshmallow
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Function 1:
void openGallry() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
Function 2 :
void galleryPermissionDialog() {
int hasWriteContactsPermission = ContextCompat.checkSelfPermission(ActivityProfile.this,
android.Manifest.permission.READ_EXTERNAL_STORAGE);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ActivityProfile.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
return;
} else {
openGallry();
}
}
Function 3 :
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(android.Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for READ_EXTERNAL_STORAGE
boolean showRationale = false;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (perms.get(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
galleryPermissionDialog();
} else {
showRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
if (showRationale) {
showMessageOKCancel("Read Storage Permission required for this app ",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
galleryPermissionDialog();
}
});
} else {
showMessageOKCancel("Read Storage Permission required for this app ",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ActivityProfile.this, "Please Enable the Read Storage permission in permission", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_CODE_MANUAL);
}
});
//proceed with logic by disabling the related features or quit the app.
}
}
} else {
galleryPermissionDialog();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Function 4 :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = imageReturnedIntent.getData();
/* final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
img_profile.setImageBitmap(selectedImage);*/
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
pictureFile = saveBitmapToFile(new File(picturePath));
Picasso.with(getApplicationContext()).load(new File(picturePath)).transform(new CircleTransform()).into(imgProfile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Function 5 :
public void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(ActivityProfile.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
file/* is not a valid MIME type. You should use / if you want to support any type of file. The files you see are unselectable because they are not of the correct MIME type.
With the introduction of virtual files in Android 7.0 (files that don't have a bytestream and therefore cannot be directly uploaded), you should most definitely add CATEGORY_OPENABLE to your Intent:
https://developer.android.com/about/versions/nougat/android-7.0.html#virtual_files
https://developer.android.com/reference/android/content/Intent.html#CATEGORY_OPENABLE
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//sets the select file to all types of files
intent.setType("*/*");
// Only get openable files
intent.addCategory(Intent.CATEGORY_OPENABLE);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,
"Choose File to Upload.."), PICK_FILE_REQUEST);
}
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
String filename =getFileName(yourfileuri);

Categories

Resources