How to set different request codes in onActivityResult? - java

I have an app that chooses a picture either from gallery or from camera and put it on an imageview. The problem is that I can't set two different request codes for the same OnActivityResult.
camera capture works, but gallery doesn't. I get this:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/272 flg=0x1 }} to activity {com.parse.starter/com.parse.starter.reportar}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.deliverResults(ActivityThread.java:3649)
Could someone help me please?? here is my code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Image from gallery...
if(requestCode == 1 && resultCode == RESULT_OK && data !=null){
Uri selectedImage = data.getData();
try {
//converts data into bitmap
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
//sets image on imageview
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmapImage);
} catch (IOException e){
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(),"Error", Toast.LENGTH_LONG).show();
}
}
//Image from camera
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(),"Error", Toast.LENGTH_LONG).show();
}
}
}

Try this
private int LOAD_IMAGE_RESULTS=1;
OnChoose Code
chooseimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 23){
boolean result= Utility.checkPermission(getActivity());
if(result) {
galleryIntent();
}
}
else {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i,LOAD_IMAGE_RESULTS); //LOAD_IMAGE_RESULTS
}
}
});
Also Code added For Permission and Set Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= 23) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
onSelectFromGalleryResult(data);
}
}
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Bitmap bitmap = null;
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
}
cursor.close();
}
else {
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == getActivity().RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
mPath = cursor.getString(cursor.getColumnIndex(filePath[0]));
//edAttach.setText(mPath.toString()); path set anywhere
cursor.close();
}
}
}
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
ivprofile.setImageBitmap(bm);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
//edAttach.setText(mPath); path set anywhere
}
cursor.close();
}
else {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mPath = cursor.getString(columnIndex).toString();
System.out.println("picturePath" + mPath);
if (!mPath.equalsIgnoreCase(null)) {
edAttach.setText(mPath);
}
cursor.close();
}
}
public boolean hasPermissionInManifest(Context context, String permissionName) {
final String packageName = context.getPackageName();
try {
final PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
final String[] declaredPermisisons = packageInfo.requestedPermissions;
if (declaredPermisisons != null && declaredPermisisons.length > 0) {
for (String p : declaredPermisisons) {
if (p.equals(permissionName)) {
return true;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
public static boolean isMediaDocument(Uri uri)
{
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),LOAD_IMAGE_RESULTS);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
galleryIntent();
} else {
//code for deny
}
break;
}
}
Or Permission In your mainfiest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Related

I am implementing file picker on android 11 and getting uri.getPath() in form of "/document/msf:1334"

1.This method gets executed successfully but it returns null.
private String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Files.FileColumns.DATA };
cursor context.getContentResolver().query(contentUri,proj, null,
null, null);
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e) {
Log.e("TAG", "getRealPathFromURI Exception : " +
e.toString());
return "";
} finally
{ if (cursor != null)
{
cursor.close();
}
}
}
onActivityresult method.
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == PICK_PDF_FILE
&& resultCode == Activity.RESULT_OK) {
// The result data contains a URI for the document or directory
// that the user selected.
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
Log.e( "Error!llllllllll", "nullll "+uri.getPath());
String path = getRealPathFromURI(s_activity,uri);
Log.e( "Error!llllllllll", "nullll "+path);
}
}
}

Android open failed: EACCES (Permission denied) when try to read a file in data/data

I need to read a file selected by user, so I use this code:
//This code is called by a button to ask the permission
private void startUpload(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_PERMISSION_GRANTED);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_PERMISSION_GRANTED);
}
}
}//startUpload
I put the relative permission in the manifest too:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I read the file in this way:
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case WRITE_PERMISSION_GRANTED: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
FileInputStream stream = new FileInputStream(toUpload.getCanonicalFile());
byte[] data = new byte[(int) toUpload.length()];
stream.read(data);
stream.close();
Log.e("FUNZIONA!!!!", "OK!");
}catch (Exception e){
Log.e("ECCEZIONE", e.getMessage());
}
} else {
Log.e("PERMISSION", "DEINED");
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
(toUpload is a file selected by the user with the file manager, in this case a downloaded image)
With the code I get this exception:
/data/data/com.android.browser/cache/2016-04-25-17-17-49-1205395195.jpg: open failed: EACCES (Permission denied)
I don't know what the problem is.
I add some details:
//this code opens the defualt file manager
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Snackbar.make(uploadView, "Nessun file manager trovato!", Snackbar.LENGTH_LONG).setAction("Response", null).show();
}
}//showFileChooser
//this is for getting the selected file
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
String path = getPath(this, uri);
toUpload = new File(path);
//Log.d("LOG", "File Path: " + path);
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}//onActivityResult
And this is the code to get the path:
private String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}//getPath
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}//getDataColumn
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}//isExternalStorageDocument
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}//isDownloadsDocument
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}//isMediaDocument
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}//isMediaDocument
What is wrong?
You are not the author of the com.android.browser app. You cannot access that app's files on internal storage. Your permissions are for external storage.
ok, I solved it! The problem was in part the emulator ... I post the code for those who had the same problem (thanks to CommonsWare for help):
//It requires a file manager installed
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
try {
startActivityForResult(intent, FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Snackbar.make(uploadView, "No file manager founded!", Snackbar.LENGTH_LONG).setAction("Response", null).show();
}
}//showFileChooser
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
uriToUpload = uri;
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}//onActivityResult
private byte[] getFileData() throws IOException{
Cursor cursor = getContentResolver().query(uriToUpload, null, null, null, null);
cursor.moveToFirst();
long size = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
cursor.close();
InputStream stream = getContentResolver().openInputStream(uriToUpload);
byte[] data = new byte[(int)size];
stream.read(data);
stream.close();
return data;
}//getFileData

java.io.FileNotFoundException while posting image from Gallery to server

I want to post image selected through camera to server using multi part .I am getting exception here
java.io.FileNotFoundException: /external/images/media/26: open failed: ENOENT (No such file or directory)
Code is given below:
//On clicking Gallery
layout_gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadImageFromGallery();
}
});
public void loadImageFromGallery() {
popupWindow.dismiss();
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
String root = Environment.getExternalStorageDirectory().toString();
Log.e("root", root);
String directory_path = root + "/cam_intent/";
File myDir = new File(directory_path);
myDir.mkdirs();
File file = new File(myDir, "MyPhoto.jpg");
fileUri = Uri.fromFile(file);
Log.e("Uri of File", String.valueOf(fileUri));
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
launchUploadActivity(true);
} else if (requestCode == RESULT_LOAD_IMG) {
fileUri = data.getData();
//File file = new File(getRealPathFromURI(NewGroupActivity.this,uri));
//fileUri = Uri.fromFile(file);
Log.e("FileUriImageGallery", String.valueOf(fileUri));
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(fileUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.groupPic);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
}
} else {
Toast.makeText(this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}
Image is shown in the ImageView but is not sent to the server as it is thrown a FileNotFoundException.
private String uploadFile() {
Log.e("upload File", "called");
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
Log.e("URL", url_create_new_group);
HttpPost httppost = new HttpPost(url_create_new_group);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
if (val == 0) {
if (fileUri != null) {
Log.e("val = ", String.valueOf(val));
File sourceFile = new File(fileUri.getPath());
if (sourceFile != null) {
Log.e("SoureFile", String.valueOf(sourceFile));
photosize = 0;
entity.addPart("image", new FileBody(sourceFile));
} else {
photosize = 1;
Toast.makeText(NewGroupActivity.this, "Please Upload Your Image", Toast.LENGTH_LONG).show();
}
}
} else {
File sourceFile = new File(picturePath);
if (sourceFile != null) {
photosize = 0;
entity.addPart("image", new FileBody(sourceFile));
} else {
photosize = 1;
Toast.makeText(NewGroupActivity.this, "Please Upload Your Image", Toast.LENGTH_LONG).show();
}
}
totalSize = entity.getContentLength();
Log.e("Total Size", String.valueOf(totalSize));
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: " + statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
Please check the code.
Solved
Updated Working Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
launchUploadActivity(true);
} else if (requestCode == RESULT_LOAD_IMG) {
Uri uri = data.getData();
//File file = new File(getRealPathFromURI(NewGroupActivity.this,uri));
//fileUri = Uri.fromFile(file);
Log.e("FileUriImageGallery", String.valueOf(uri));
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(uri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.groupPic);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
}

How to get image from gallery which supports for API>=19 & API<19 both?

Image is not importing, every time when I pic image from gallery in Android.
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, LOAD_IMAGE_RESULTS);
super.onActivityResult(requestCode, resultCode, data);
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK
&& data != null) {
imgUri = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(imgUri, filePath, null,
null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor
.getColumnIndex(filePath[0]));
bmp = BitmapFactory.decodeFile(imagePath);
cursor.close();
}
image is not importing every time ,some bmp sets nothing on imageview.
how to get image from gallery which supports for API>=19 & API<19 both...
This code'll solve the problem for SDK < API11, SDK >= 11 && SDK < 19 and SDK > 19
Declare it Globally
public final int GALLERY_PHOTO = 2;
Bitmap newbitmap;
private Uri fileUri;
Use this Method to Start Image chooser
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
GALLERY_PHOTO);
}
Use this condition in Default #Overide onActivityResult(int requestCode, int resultCode, Intent data)
if (requestCode == GALLERY_PHOTO) {
if (resultCode == RESULT_OK) {
// SDK < API11
if (Build.VERSION.SDK_INT < 11) {
try {
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(
Yourclassname.this,
data.getData());
setTextViews(Build.VERSION.SDK_INT, data.getData()
.getPath(), realPath);
} catch (Exception e) {
e.printStackTrace();
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();
newbitmap = BitmapFactory.decodeFile(filePath);
imageview.setImageBitmap(newbitmap);
}
}
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19) {
try {
realPath = RealPathUtil.getRealPathFromURI_API11to18(
yourclassname.this,
data.getData());
setTextViews(Build.VERSION.SDK_INT, data.getData()
.getPath(), realPath);
} catch (Exception e1) {
e1.printStackTrace();
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();
newbitmap = BitmapFactory.decodeFile(filePath);
imageview.setImageBitmap(newbitmap);
}
}
else {
try {
realPath = RealPathUtil.getRealPathFromURI_API19(
yourclassname.this,
data.getData());
setTextViews(Build.VERSION.SDK_INT, data.getData()
.getPath(), realPath);
} catch (Exception e) {
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();
newbitmap = BitmapFactory.decodeFile(filePath);
imageview.setImageBitmap(newbitmap);
}
}
// end
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Canceled",
Toast.LENGTH_SHORT).show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Oops!! Failed to pick Image", Toast.LENGTH_SHORT).show();
}
}
Include this method in your class
private void setTextViews(int sdk, String uriPath, String realPath) {
Uri uriFromPath = Uri.fromFile(new File(realPath));
fileUri = uriFromPath;
try {
newbitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(fileUri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
imageview.setImageBitmap(newbitmap);
Log.d("Status", "Build.VERSION.SDK_INT:" + sdk);
Log.d("Status", "URI Path:" + fileUri);
Log.d("Status", "Real Path: " + realPath);
}
Create this Helper Methods in RealPathUtil.class
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.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();
return filePath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor 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);
}
}
Hope this will solve your Problem.

Android KitKat Image selecting not returning anything

I've been trying to get the absolute image path of a image selected in the gallery on KitKat but it doesn't seem to be working out. My variable IMAGE_FILEPATH is always "" after whatever I do. Here's the code for my onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) return;
if (null == data) return;
Uri originalUri = null;
if (requestCode == 1) {
//JB!!!
Uri uri = data.getData();
if (uri != null) {
try {
// User had pick an image.
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver()
.query(uri,
filePathColumn, null, null, null);
cursor.moveToFirst();
IMAGE_FILEPATH = cursor.getString(0);
cursor.close();
} catch (Exception e) {
Crouton.makeText(this, "Failed to get image", Style.ALERT).show();
}
}
} else if (requestCode == 2) {
//KK!!!
Uri uri = data.getData();
if (uri != null) {
try {
if( uri == null ) {
IMAGE_FILEPATH = uri.getPath();
} else {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
IMAGE_FILEPATH = cursor.getString(column_index);
} else {
IMAGE_FILEPATH = uri.getPath();
}
}
} catch (Exception e) {
Crouton.makeText(this, "Failed to get image", Style.ALERT).show();
}
}
}
Resource.toast(IMAGE_FILEPATH);
super.onActivityResult(requestCode, resultCode, data);
}
What's going wrong? I've tried multiple solutions and nothing seems to work.
In KitKat the Gallery returns an URI like this : content://com.android.providers.media.documents/document/image:1
instead of :
content://media/external/images/media/1
So, here is what you can write under KK to make it works :
if (uri != null) {
try {
if( uri == null ) {
IMAGE_FILEPATH = uri.getPath();
} else {
// get the id of the image selected by the user
String wholeID = DocumentsContract.getDocumentId(data.getData());
String id = wholeID.split(":")[1];
String[] projection = { MediaStore.Images.Media.DATA };
String whereClause = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().query(getUri(), projection, whereClause, new String[]{id}, null);
if( cursor != null ){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
IMAGE_FILEPATH = cursor.getString(column_index);
}
cursor.close();
} else {
IMAGE_FILEPATH = uri.getPath();
}
}
} catch (Exception e) {
Crouton.makeText(this, "Failed to get image", Style.ALERT).show();
}
}
And the function I used :
private Uri getUri() {
String state = Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
}
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
These posts helped me : retrieve absolute path when select image from gallery kitkat android and Get real path from URI, Android KitKat new storage access framework
moveToFirst returns a boolean indicating if moving to that position resulted in data.
boolean haveData;
haveData = cursor.moveToFirst();
if (haveData) {
cursor.getString(.....
That's what you should be doing, which is just good, defensive programming. Now, why your cursor is empty, that's going to take more digging to your contentResolver.

Categories