Path file for opening files in activityforresult android 8 - java

Im trying to get the path file for showing in a recycler view using intent for choosing file and activityresult for response of that action so my code works in android 4> until 7< and it works fine for those versions but in 7>= there is a problem with that code , especially in android 9.
public void openGallery() {
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select file to upload "),
SettingsUtil.ACTIVITY_GALLERY);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SettingsUtil.ACTIVITY_GALLERY && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver()
.query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
String code = year + "-" + reservation + "-" + (counter++);
File auxFile = new File(picturePath);
}
}
i expect to String picturePath = cursor.getString(columnIndex); get the path like old android vesions 4+ <7 but in those new versions there is a problem there when working in last versions

Related

How to get Real path from URI android Lollipop

I've tried this but with no luck.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
nameView.setText(selectedImage.toString());
realPath = getRealPathFromURI(this, selectedImage);
Toast.makeText(MainActivity.this, realPath, Toast.LENGTH_LONG).show();
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
I am getting null when I display in TOAST.
I am running Lollipop.
Please could someone explain in detail on how to do this.
I am able to get the URI without any problems but my only issue is to not being able to convert it to a real path to store in my database.
Thanks
This problem occurs mainly for google native devices such as Nexus because in these devices the only image library is google photos. In google photos you get to choose not only those images which are present on your device but also those photos which are stored on cloud storage too. Try the below mentioned updated code of yours and let me know if it worked or not.
Your intent should have action as Intent.ACTION_GET_CONTENT
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ATTACHMENT_PHOTO_GALLERY && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
nameView.setText(selectedImage.toString());
String realPath = getRealPathFromURI(this, selectedImage);
Toast.makeText(MainActivity.this, realPath, Toast.LENGTH_LONG).show();
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
String path = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
//The above code will fail to get file path if the file is selected from google photos.
//Then this will be the alternative approach
if (path == null && contentUri.toString().startsWith("content://com.google.android.apps.photos.content")) {
Bitmap requiredImage = null;
//Below key should be used for saving the newly downloaded image path as
//photoIdentificationKey as Key parameter and newly generated path as Value.
//An additional check should be implemented on your storage that whether any local
//path exists for corresponding photoIdentificationKey, if yes then use the existing
//local path else download new image.
String photoIdentificationKey = Uri.parse(contentUri.getLastPathSegment()).getLastPathSegment();
BitmapFactory.Options options = new BitmapFactory.Options();
InputStream inputStream;
try {
inputStream = getApplication().getContentResolver().openInputStream(contentUri);
requiredImage = BitmapFactory.decodeStream(inputStream, null, options);
//Save the newly downloaded image to your isolated storage and return the path
//on which this new image has been saved.
inputStream.close();
path = saveAndReturnPathForSavedImage(requiredImage);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return path;
}
private String saveAndReturnPathForSavedImage(Bitmap bmp) {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream out = null;
File file = new File(path, "IMAGE"+ Calendar.getInstance().getTime()+".jpg"); // the File to save to
try {
out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file.getPath();
}
If your Intent data data is not null then you can try this.
I've used this code to get image path from gallery, and its working in all devices.
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.e("path of image from gallery......******************.........", picturePath + "");
Note: Be sure your data should not be null otherwise it will give NullPointerException.

TransactionTooLargeException while copying file Android

My aim is to browse a file and copy it, and paste it in a other folder.
To browse the file I have used Intent as shown below
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "DEMO"), 1001);
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
Uri currFile = data.getData();
}
}
Now I want to copy the file for that I have to get file real path from URI.
(I am passing file real path to java FileInputStream )
To convert Uri to real path I did as shown below
public static String getPath(Context cx,Uri uri) {
String filePath = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ){
String wholeid = DocumentsContract.getDocumentId(uri);
String id = wholeid.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = cx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}else{
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = cx.getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
return uri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
filePath = cursor.getString(idx);
}
}
return filePath;
}
If the file is more than 10kb it is giving TransactionTooLargeException.
My question is how can I browse and copy a file and paste in a folder without getting TransactionTooLargeException.
Is there any good method to do that.

onActivityResult not called under API level 17

I have a class for uploading image to server but i can't choose image from gallery.It's properly working on API Level +17 but not working on API Level -17
thoose are my codes
CustomJavascriptClass
public String uploadImage(){
Activity activity = (Activity)context;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
activity.startActivityForResult(photoPickerIntent, 100);
...
MainActivity
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(requestCode == 100){
try{
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Log.i("File", filePath);
if (Build.VERSION.SDK_INT >= 17){
HappyJavaScriptInterface.attachment = new File(filePath);
HappyJavaScriptInterface.uploadProcess = 1;
}
else
{
HappyJavaScriptInterfaceUnder17.attachment = new File(filePath);
HappyJavaScriptInterfaceUnder17.uploadProcess = 1;
}
}
catch(Exception ex){
if (Build.VERSION.SDK_INT >= 17){
HappyJavaScriptInterface.uploadProcess = 1;
}
else
{
HappyJavaScriptInterfaceUnder17.uploadProcess = 1;
}
}
}
It's working properly on android 4.2.2 emulator but not working on 2.3.3
Thanks
Try to set android:noHistory="false" in your manifest for MainActivity

insert a picture from android to database

in my project, i got a problem about insert a picture from android to database.
i have success insert a picture from gallery mobile but not work insert from a camera mobile.
This my source code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
pathToOurFile = filePath;
format = filePath.substring(filePath.lastIndexOf(".") + 1,
filePath.length());
this.imGambar.setImageBitmap((Bitmap) data.getExtras().get(
"data"));
} else if (requestCode == SELECT_FILE) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
pathToOurFile = filePath;
format = filePath.substring(filePath.lastIndexOf(".") + 1,
filePath.length());
this.imGambar
.setImageBitmap(BitmapFactory.decodeFile(filePath));
}
}
}
This method doesn't work fine to get Uri in request camera activity result. You'd better use :
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
And in the onActivityResult :
String path = mImageCaptureUri.toString();
where
Uri mImageCaptureUri ;
is a global variable.
Hope it helps...

Android intent.getData() Nullpointer exceptipon

I have an android app that start the smartphone camera
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST );
To display the taken picture I use this piece of code,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
setImage=true;
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
if(data!=null)
{
ImageView image = (ImageView) findViewById(R.id.imagePreview);
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
image.setImageBitmap(mImageBitmap);
}
}
}
This works pretty fine but if i want to get the path of the taken picture, i have to use (intent)data.getData() but this returns a null value. what should i do to solve this problem?
Try this hope it helps you.
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
String imageName = picturePath.substring(picturePath.lastIndexOf(
"/", picturePath.length()));
Try out as below:
Bitmap m_photo = (Bitmap) p_data.getExtras().get("data");
if (m_photo != null)
{
ByteArrayOutputStream m_upByteArrayOutputStream = new ByteArrayOutputStream();
m_photo.compress(Bitmap.CompressFormat.PNG, 40, m_upByteArrayOutputStream);
Drawable m_imageFromCamera = new BitmapDrawable(m_photo);
image.setBackgroundDrawable(m_photo);
}
EDITED:
To get the Path of the image try out below code:
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex); <---- Here is your image path.
cursor.close();

Categories