Camera folder image not showing in imageview - android

I am trying to set an image to an imageview that a user selects from their gallery. However all the images seem to load to my imageview except when I select an image from the camera folder. It doesn't put the image into my imageview. Refer to the following image http://i.stack.imgur.com/h6QGG.jpg
Call of intent
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
// Start the Intent
Log.d(TAG,"STARTING ACTIVITY FOR RESULT");
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
Log.d(TAG,"IN ON ACTIVIY RESULT");
super.onActivityResult(requestCode, resultCode, data);
try {
Log.d(TAG, "IN INTERESTS ON ACTIVITY RESULT");
if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
File file = new File(picturePath);
bmOptions.inJustDecodeBounds = true;
Bitmap original = BitmapFactory.decodeFile(picturePath);
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
Bitmap newBm = Bitmap.createScaledBitmap(original, 900, 1280, true);
newBm.compress(Bitmap.CompressFormat.JPEG, 90, ostream);
ostream.close();
BitmapFactory.decodeFile(picturePath, bmOptions);
iconpic.setImageBitmap(newBm);
Toast.makeText(getContext(), picturePath, Toast.LENGTH_SHORT)
.show();
cursor.close();
SharedPreferences appPrefs = getContext().getSharedPreferences("com.example.gcmclient_preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = appPrefs.edit();
prefsEditor.putString("iconPath", picturePath);
prefsEditor.commit();
// String picturePath contains the path of selected Image
}
}
catch (Exception e){
e.printStackTrace();
}
}

Hope this will work.
Uri imageUri;
File file;
public int CAMERA_INTENT_CALLED = 100;
public int GALLERY_INTENT_CALLED = 101;
public int GALLERY_KITKAT_INTENT_CALLED = 102;
if (Build.VERSION.SDK_INT < 19) {
Intent intent = new Intent();
intent.setType("image/jpeg");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select image to promote"),
GALLERY_INTENT_CALLED);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/jpeg");
startActivityForResult(intent,
GALLERY_KITKAT_INTENT_CALLED);
}
onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Uri originalUri = null;
if (requestCode == GALLERY_INTENT_CALLED) {
if (data.getData() != null) {
originalUri = data.getData();
String path = getRealPathFromURI(originalUri);
setImageBitmap(path);
originalUri = null;
}
} else if (requestCode == GALLERY_KITKAT_INTENT_CALLED) {
if (data.getData() != null) {
originalUri = data.getData();
String path = getPath(this, originalUri);
setImageBitmap(path);
originalUri = null;
}
} else if (requestCode == CAMERA_INTENT_CALLED) {
Uri selectedImage = imageUri;
try {
if (selectedImage != null) {
getContentResolver().notifyChange(selectedImage, null);
String path = getRealPathFromURI(selectedImage);
Log.e("Imagepath Camera", path);
setImageBitmap(path);
imageUri = null;
}
} catch (Exception e) {
Log.e("Camera", e.toString());
}
}
}
API <19 and above GalleryImage selected
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = getContentResolver().query(contentURI, null, null,
null, null);
if (cursor == null) { // Source is Dropbox or other similar local file
// path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor
.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
KITKAT and above GalleryImage selected
public static 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];
}
// TODO handle non-primary volumes
}
// 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;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
/**
* #param uri
* The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
/**
* #param uri
* The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
}

Related

While selecting a PDF file from recent files folder in Android 11 is giving NulllPointException:Uri

The below shows the way how I tried and it gives me NulllPointException: Uri While selecting a PDF file from the recent files folder in Android 11.
Please let me know How to get pdf file path from recent folder
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
//todo when permission is granted
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] mimetypes = {"image/*", "application/*"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
startActivityForResult(intent, REQ_PDF);
} else {
//request for the permission
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] mimetypes = {"image/*", "application/*"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
startActivityForResult(intent, REQ_PDF);
}
}
});
#SuppressLint({"SetTextI18n", "NewApi"})
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
InputStream inputStream = null;
try {
if (requestCode == REQ_PDF && resultCode == RESULT_OK && data != null) {
path = data.getData();
inputStream = this.getContentResolver().openInputStream(path);
byte[] pdfInBytes = new byte[inputStream.available()];
inputStream.read(pdfInBytes);
// Toast.makeText(getContext(), ""+value, Toast.LENGTH_SHORT).show();
String encodedCode = Base64.encodeToString(pdfInBytes, Base64.DEFAULT);
filePath = PathUtil.getPathFromUri(this, path);
// filePath= FileUtils.getPath(this,path);
if (filePath == null) {
// Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
SharedPrefMannager.showAlertDialog(InvoiceGenerationActivity.this, "Alert!", "Please select a file from internal storage", true);
} else {
file = new File(filePath);
file_size = Integer.parseInt(String.valueOf(file.length() / 1024));
}
tv_attachFile.setText("Change File");
tv_fileLocation.setVisibility(View.VISIBLE);
tv_fileLocation.setText(filePath);
//Toast.makeText(getContext(), encodedCode, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(InvoiceGenerationActivity.this, "Something went wrong " + e, Toast.LENGTH_SHORT).show();
}
}
public class PathUtil
{
private static Uri contentUri = null;
#SuppressLint("NewApi")
public static String getPathFromUri(final Context context, final Uri uri) {
// check here to is it KITKAT or new version
final boolean isKitKatOrAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
String selection = null;
String[] selectionArgs = null;
// DocumentProvider
if (isKitKatOrAbove && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
final String type = split[0];
String fullPath = getPathFromExtSD(split);
if (fullPath != "") {
return fullPath;
} else {
return null;
}
//return getPathFromExtSD(split);
/* String fullPath =Environment.getExternalStorageState() + "/" + split[1];
if (fullPath != "") {
return fullPath;
} else {
return null;
}*/
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final String id;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String fileName = cursor.getString(0);
String path = getExternalStorageDirectory().toString() + "/Download/" + fileName;
if (!TextUtils.isEmpty(path)) {
return path;
}
}
} finally {
if (cursor != null)
cursor.close();
}
id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads",
"content://downloads/all_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
try {
final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
//In Android 8 and Android P the id is not a number
return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
}
}
}
} else {
final String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.parseLong(id)); //public
}
if (contentUri != null) {
return getDataColumn(context, contentUri, null, null);
}
} catch (NumberFormatException e) {
e.printStackTrace();
Toast.makeText(context, "" + e, Toast.LENGTH_SHORT).show();
}
}
}
// 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 ("application".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; //MediaStore.Video.Media.EXTERNAL_CONTENT_URI
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection,
selectionArgs);
} else if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {
return getMediaFilePathForN(uri, context);
} else {
return getDataColumn(context, uri, null, null);
}
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
private static boolean fileExists(String filePath) {
File file = new File(filePath);
return file.exists();
}
private static String getPathFromExtSD(String[] pathData) {
String type = pathData[0];
String relativePath = "/" + pathData[1];
String fullPath = "";
if ("primary".equalsIgnoreCase(type)) {
fullPath = getExternalStorageDirectory() + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
}
fullPath = System.getenv("SECONDARY_STORAGE") + relativePath;
if ((null == fullPath) || (fullPath.length() == 0)) {
fullPath = System.getenv("SECONDARY_SDCARD_STORAGE");
return fullPath;
}
/* if (fileExists(fullPath)) {
return fullPath;
}*/
fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath;
if ((null == fullPath) || (fullPath.length() == 0)) {
fullPath = System.getenv("EXTERNAL_SDCARD_STORAGE");
return fullPath;
}
/* if (fileExists(fullPath)) {
return fullPath;
}*/
return fullPath;
}
private static String getDriveFilePath(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
InputStream inputStream = null;
FileOutputStream outputStream = null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getCacheDir(), name);
try {
inputStream = context.getContentResolver().openInputStream(uri);
outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
}
}
}
return file.getPath();
}
private static String getMediaFilePathForN(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getFilesDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return file.getPath();
}
private 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);
}
} catch (Exception e) {
// Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
private static boolean isGoogleDriveUri(Uri uri) {
return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
}
}
Any help would be appreciated. I am testing on an android R device. Why is it that when selecting the file from a RECENT section in the file browser I am not getting any file path meanwhile selecting the same file in the STORAGE section is returning file path?
I have added only that else part and it's working fine. thank you for helping. referece
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;
}else {
contentUri = MediaStore.Files.getContentUri("external");
}

Android variable at "onActivityResult" sometime null value on KITKAT

private void openCamera(int imageArray){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/SurveyDA/assets/images","absen_" +
System.currentTimeMillis() + ".jpg"));
Log.d("ddddd : ", String.valueOf(fileUri));
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, imageArray);
}
when I want open camera, I set the fileuri, and Log success return uri
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
//getting bitmap object from uri
Log.d("ddddd : ", String.valueOf(fileUri));
bitmapImage[requestCode] = MediaStore.Images.Media.getBitmap(this.getContentResolver(), fileUri);
// Initialize a new ByteArrayStream
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress the bitmap with JPEG format and quality 50%
bitmapImage[requestCode].compress(Bitmap.CompressFormat.JPEG,60,stream);
byte[] byteArray = stream.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
bitmapImage[requestCode] = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), false);
//displaying selected image to imageview
imageViews[requestCode].setImageBitmap(bitmapImage[requestCode]);
//calling the method uploadBitmap to upload image
} catch (IOException e) {
e.printStackTrace();
}
}else if(resultCode == Activity.RESULT_CANCELED) {
// User Cancelled the actiongetUriForFile
}
}
but in onActivityResult variable fileuri sometimes get null, and sometimes success return uri. And when I try in other phone Android 8.0.0, there no error.
how to fix that?
java.lang.RuntimeException: Unable to resume activity {com.example.surveyonlineda/com.example.surveyonlineda.Activity.AbsenActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.example.surveyonlineda/com.example.surveyonlineda.Activity.AbsenActivity}: java.lang.NullPointerException
Refer this Document for your issue you will get best solution
as I see, the fileUri is not returned by onActivityResult. You create it before start your cameraIntent. So in case your activity has been destroyed, the fileUri will null. To prevent it, I think you should use onSaveInstanceState to save the fileUri.
Here is an example to save the string fileUri
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of fileUri from saved state
fileUri = savedInstanceState.getString(FILE_URI);
} else {
// Probably initialize values for a new instance
}
}
#Override protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(FILE_URI, fileUri);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
You can try it. it worked for me
Step 1. Create class GetPathFromUri.class
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.*;
public class GetPathFromUri {
#SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
#SuppressLint("ObsoleteSdkInt") 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];
}
if ("raw".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
if ("5D68-9217".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
if (id != null && id.startsWith("raw:")) {
return id.substring(4);
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
try {
String path = getDataColumn(context, contentUri, null, null);
if (path != null) {
return path;
}
} catch (Exception e) {}
}
// path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
String fileName = getFileName(context, uri);
File cacheDir = getDocumentCacheDir(context);
File file = generateFileName(fileName, cacheDir);
String destinationPath = null;
if (file != null) {
destinationPath = file.getAbsolutePath();
saveFileFromUri(context, uri, destinationPath);
}
return destinationPath;
}
// 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 getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
private static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
final String column = "_data";
final String[] projection = {column};
try (Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null)) {
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static String getFileName(#NonNull Context context, Uri uri) {
String mimeType = context.getContentResolver().getType(uri);
String filename = null;
if (mimeType == null && context != null) {
String path = getPath(context, uri);
if (path == null) {
filename = getName(uri.toString());
} else {
File file = new File(path);
filename = file.getName();
}
} else {
Cursor returnCursor = context.getContentResolver().query(uri, null,
null, null, null);
if (returnCursor != null) {
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
filename = returnCursor.getString(nameIndex);
returnCursor.close();
}
}
return filename;
}
public static String getName(String filename) {
if (filename == null) {
return null;
}
int index = filename.lastIndexOf('/');
return filename.substring(index + 1);
}
public static File getDocumentCacheDir(#NonNull Context context) {
File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
logDir(context.getCacheDir());
logDir(dir);
return dir;
}
public static final String DOCUMENTS_DIR = "documents";
static final String TAG = "FileUtils";
private static final boolean DEBUG = false; // Set to true to enable logging
private static void logDir(File dir) {
if (!DEBUG) return;
Log.d(TAG, "Dir=" + dir);
File[] files = dir.listFiles();
for (File file : files) {
Log.d(TAG, "File=" + file.getPath());
}
}
#Nullable
public static File generateFileName(#Nullable String name, File directory) {
if (name == null) {
return null;
}
File file = new File(directory, name);
if (file.exists()) {
String fileName = name;
String extension = "";
int dotIndex = name.lastIndexOf('.');
if (dotIndex > 0) {
fileName = name.substring(0, dotIndex);
extension = name.substring(dotIndex);
}
int index = 0;
while (file.exists()) {
index++;
name = fileName + '(' + index + ')' + extension;
file = new File(directory, name);
}
}
try {
if (!file.createNewFile()) {
return null;
}
} catch (IOException e) {
Log.w(TAG, e);
return null;
}
logDir(directory);
return file;
}
private static void saveFileFromUri(Context context, Uri uri, String destinationPath) {
InputStream is = null;
BufferedOutputStream bos = null;
try {
is = context.getContentResolver().openInputStream(uri);
bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
byte[] buf = new byte[1024];
is.read(buf);
do {
bos.write(buf);
} while (is.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) is.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Step 2:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
String path = GetPathFromUri.getPath(this, data.getData())
Glide.with(this).load(path).into(imageView);
// Glide is library https://github.com/bumptech/glide
} catch (IOException e) {
e.printStackTrace();
}
}else if(resultCode == Activity.RESULT_CANCELED) {
// User Cancelled the actiongetUriForFile
}
}

How to take photo from fragment

I want to take photo from fragment but if I use follow codes onActivityResult Intent data return null. I didn't figure out why Intent data return null?
CameraFragement.java
private void takePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getContext(),
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
String imagePath;
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
imagePath = image.getAbsolutePath();
return image;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // this Intent data return null
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
Intent intent = new Intent(getActivity(), PostActivity.class);
intent.setData(data.getData());
startActivity(intent);
}
}
If I use this follow code instead of above takePictureIntent Intent data return with extras but data.getData() return null. I don't want to return data with extras. I don't want to Bitmap data. I need datas Uri form. I need data.getData(). This follow code used to before but now it's not work. I update my application always with Android SDK. I think this is the reason but what is the solution?
private void takePictureIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
Edit: I tried almost everything but Intent data still return null. I am using follow code with first code example for now. You can use this, it's works fine. If you have a solution for Intent data please don't forget to notice me.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
File file = new File(imagePath);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(getActivity(), PostActivity.class);
intent.setData(uri);
startActivity(intent);
}
//capture image
public void requestTakePhoto() {
//SettingsManager.sharedInstance().TAKE_PHOTO = true;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
final File photoFile;
try {
photoFile = createImageFile();
}
catch (IOException e) {
// Error occurred while creating the File
Log.e("ChatActivity", "Unable to create photo file", e);
return;
}
// Continue only if the File was successfully created
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(intent, REQ_TAKE_PHOTO);
}
}
//save captured image
private Uri mPhotoLocation;
private File createImageFile() throws IOException {
final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(newDate());
final String imageFileName = timeStamp + "filename";
final File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
final File image = File.createTempFile(imageFileName, ".jpg", storageDir);
mPhotoLocation = Uri.fromFile(image);
return image;
}
//handle result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode) {
case REQ_PICK_IMAGE:
if (resultCode == Activity.RESULT_OK && data.getData() != null) {
Uri uri =data.getData();
//do your work with data
// String filePath = getRealPathFromUri(uri);
//if (filePath != null && !filePath.isEmpty()) {
// Uri fileUri = Uri.parse(filePath);
//sendImageMessage(fileUri);
}
}
break;
case REQ_TAKE_PHOTO:
if (resultCode == Activity.RESULT_OK ) {
//do your work with data
String filePath = getRealPathFromUri(mPhotoLocation);
if (filePath != null && !filePath.isEmpty()) {
Uri fileUri = Uri.parse(filePath);
sendImageMessage(fileUri);
}
mPhotoLocation = null;
}
break;
case REQ_FILE_ATTACHMENT:
if (resultCode == Activity.RESULT_OK && data.getData() != null) {
Uri uri = data.getData();
//String filePath = getRealPathFromUri(uri);
//if (filePath != null && !filePath.isEmpty()) {
//Uri fileUri = Uri.parse(filePath);
//sendFileMessage(fileUri);
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
//get realpath
public String getRealPathFromUri(final Uri uri) {
// DocumentProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(getActivity(), 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(getActivity(), 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(getActivity(), contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(getActivity(), uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
private 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;
}
private boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
the requestcode is lost in the fragment, you need to use activity context:
getActivity().startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
This library will help you to fetch image from Camera or Storage to view in Activity or Fragment.
Its provide very simple methods t do that,
https://github.com/coomar2841/image-chooser-library

Select Image from gallery in Android Fragment

I want to select gallery intent in fragment.when user choose option to select image from gallery then gallery opens and immediately onActivityResult of fragment is being called.and when user pick image then onActivityResult() is not called.So i am not able to select image from gallery.
Belo is my code to open gallery -
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("video/, images/");
startActivityForResult(intent, 2);
and here is my onActivityResult-
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult"); // not printed
Toast.makeText(mContext, "aaaa"+requestCode, Toast.LENGTH_SHORT).show();
}
What the problem in my code.
Thanks in advance.
Use this to open the android image chooser:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY_INTENT_CALLED);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_KITKAT_INTENT_CALLED);
}
and for onActivityResult use this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Cursor cursor = null;
if (resultCode != Activity.RESULT_OK)
return;
if (data == null)
return;
Uri originalUri = null;
if (requestCode == GALLERY_INTENT_CALLED && data != null) {
originalUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
cursor = getActivity().getContentResolver().query(originalUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
Log.d("path of uri", filePath);
} else if (requestCode == GALLERY_KITKAT_INTENT_CALLED && data != null) {
originalUri = data.getData();
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getActivity().getContentResolver().takePersistableUriPermission(
originalUri, takeFlags);
Log.d("Uri: ", originalUri.toString());
filePath = getPath(getActivity(), originalUri);
Log.d("filepath", filePath);
}
}
#SuppressLint("NewApi")
public static 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];
}
// TODO handle non-primary volumes
}
// 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 getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
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 column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
# I am showing you an example in which i used an ImageView to show image result .There are two methods used 1.From camera and 2.From SD card #
public void camera(View view) {
Log.i("SonaSys", "startCameraActivity()");
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
public void gallery(View view) {
String path = Environment.getExternalStorageDirectory()
+ "/images/imagename.jpg";
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
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();
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();
bitmap = BitmapFactory.decodeFile(picturePath);
image.setImageBitmap(bitmap);
if (bitmap != null) {
ImageView rotate = (ImageView) findViewById(R.id.rotate);
rotate.setVisibility(View.VISIBLE);
}
} else {
Log.i("SonaSys", "resultCode: " + resultCode);
switch (resultCode) {
case 0:
Log.i("SonaSys", "User cancelled");
break;
case -1:
onPhotoTaken();
break;
}
}
}
protected void onPhotoTaken() {
// Log message
Log.i("SonaSys", "onPhotoTaken");
taken = true;
imgCapFlag = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile(path, options);
image.setImageBitmap(bitmap);
}
use this code for choose image,
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select image"),
PICK_IMAGE);
Since Activity gets the result of onActivityResult(), you will need to override the activity's onActivityResult() and call super.onActivityResult() to propagate to the respective fragment for unhandled results codes or for all.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
To help others who are struggling with this bug, i would suggest the following:
1. The launch mode of your fragment activity
if launch mode of your activity is the "singleInstance"
in that case the onActivityResult will be called automatically once you leave the activity and goes to activity where you are supposed to pick the image. This is true for the camera intent also. Try to change your launch mode to "singleTop" or anything as an alternative to the launch mode that you have right now. This way what will happen that your activityOnResult will be called only when you finish up picking the image. Also the result will be return to the fragment only from where you have called the startActivityForResult. I will suggest you to consider to implement the dialogueFragment for giving option to user to pick the image or click image
2. The how have you called the startActivityForResult
Its another interesting thing, if you call your startActivityResult from fragment using the local context of the fragment the result will be returned back to the fragment but if you call it using the fragment activity context like getActivity().startActivityResult the result will be passed back to the parent fragment activity. So it depends upon you where you want to handle it.
Other important thing, do call the
super.onActivityResult(requestCode, resultCode, data);
in your method where you are getting the result.
Other than these try following the suggestion that other has provided for picking the image using the proper intent.

Android 4.4.2 - camera uri return null and also cropping feature not working?

I am trying to click image from camera and show into imageview but onactivityresult URI return null. BUt below code runs fine on JellyBean , ICS with cropping feature .
Calling intent
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
pickIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// we will handle the returned data in onActivityResult
String pickTitle = "Select or take a new Picture";
// startActivityForResult(captureIntent, 1);
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]
{ captureIntent });
startActivityForResult(chooserIntent, GlobalVariables.GALLERY_MODE);
onActivityResult
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
try
{
if (resultCode == RESULT_OK)
{
// user is returning from capturing an image using the camera
if (requestCode == GlobalVariables.GALLERY_MODE)
{
// get the Uri for the captured image
picUri = data.getData();
System.out.println("picUri ======= => "+picUri);
boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if(isKitKat)
{
System.out.println(new GraphicsUtil().getPath(RegistrationActivity.this, picUri));
String filePath = new GraphicsUtil().getPath(RegistrationActivity.this, picUri);
System.out.println("filepath => "+filePath);
bitmapPreview = null;
bitmapPreview = BitmapFactory.decodeFile(filePath);
System.out.println("bitmapPreview => "+bitmapPreview );
imageViewUser.setImageBitmap(new GraphicsUtil().getCircleBitmap(GraphicsUtil.decodeSampledBitmapFromResource(filePath,
120, 120)));
}
else
{
performCrop(picUri, PIC_CROP, RegistrationActivity.this);
}
}
// user is returning from cropping the image
else if (requestCode == PIC_CROP)
{
String filePath = new File (Environment.getExternalStorageDirectory() + "/temporary_holder.jpg").getAbsolutePath();
bitmapPreview = null;
bitmapPreview = BitmapFactory.decodeFile(filePath);
imageViewUser.setImageBitmap(new GraphicsUtil().getCircleBitmap(GraphicsUtil.decodeSampledBitmapFromResource(filePath,
120, 120)));
// imageViewUser.setImageBitmap(new
// GraphicsUtil().getCircleBitmap(bitmapPreview));
File f = new File(Environment.getExternalStorageDirectory() + "/temporary_holder.jpg");
if (f.exists())
{
f.delete();
}
}
}
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
GraphicsUtil.java
public class GraphicsUtil
{
/*
* Draw image in circular shape Note: change the pixel size if you want
* image small or large
*/
public Bitmap getCircleBitmap(Bitmap bitmap)
{
Bitmap output;
Canvas canvas = null;
final int color = 0xffff0000;
final Paint paint = new Paint();
Rect rect = null;
if (bitmap.getHeight() > 501)
{
output = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(output);
rect = new Rect(0, 0, 500, 500);
}
else
{
//System.out.println("output else =======");
bitmap = Bitmap.createScaledBitmap(bitmap, 500, 500, false);
output = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(output);
rect = new Rect(0, 0, 500, 500);
}
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
paint.setDither(true);
paint.setFilterBitmap(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth((float) 1);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth)
{
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight)
{
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
#SuppressLint("NewApi")
public 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];
}
// TODO handle non-primary volumes
}
// 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;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
public 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;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
logcat output when clicking image and select image on android 4.4.2 os:-
05-08 17:25:55.697: I/System.out(20894): picUri ======= => null
05-08 17:25:55.698: W/System.err(20894): java.lang.NullPointerException
05-08 17:25:55.711: W/System.err(20894): at android.provider.DocumentsContract.isDocumentUri(DocumentsContract.java:587)
05-08 17:25:55.712: W/System.err(20894): at com.asiaelites.utils.GraphicsUtil.getPath(GraphicsUtil.java:119)
05-08 17:25:55.712: W/System.err(20894): at com.asiaelites.RegistrationActivity.onActivityResult(RegistrationActivity.java:489)
05-08 17:25:55.712: W/System.err(20894): at android.app.Activity.dispatchActivityResult(Activity.java:5446)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.deliverResults(ActivityThread.java:3442)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2802)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2859)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2274)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.access$800(ActivityThread.java:139)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
05-08 17:25:55.712: W/System.err(20894): at android.os.Handler.dispatchMessage(Handler.java:102)
05-08 17:25:55.712: W/System.err(20894): at android.os.Looper.loop(Looper.java:136)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.main(ActivityThread.java:5102)
05-08 17:25:55.712: W/System.err(20894): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 17:25:55.713: W/System.err(20894): at java.lang.reflect.Method.invoke(Method.java:515)
05-08 17:25:55.713: W/System.err(20894): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-08 17:25:55.713: W/System.err(20894): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-08 17:25:55.713: W/System.err(20894): at dalvik.system.NativeStart.main(Native Method)
follow below link :-
Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT
This work for Kitkat
public class YourActivity extends Activity{
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browsepicture);
imageView = (ImageView)findViewById(R.id.imageView1);
((Button) findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
if (Build.VERSION.SDK_INT < 19) {
selectedImagePath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
imageView.setImageBitmap(bitmap);
}
else {
ParcelFileDescriptor parcelFileDescriptor;
try {
parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
imageView.setImageBitmap(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public String getPath(Uri uri) {
if( uri == null ) {
return null;
}
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();
return cursor.getString(column_index);
}
return uri.getPath();
}
}
For Cropping image
private void cropImage() {
// Use existing crop activity.
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(capturedImageUri, IMAGE_UNSPECIFIED);
// Specify image size
intent.putExtra("outputX", IMAGE_DIMENSION);
intent.putExtra("outputY", IMAGE_DIMENSION);
// Specify aspect ratio, 1:1
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
// REQUEST_CODE_CROP_PHOTO is an integer tag you defined to
// identify the activity in onActivityResult() when it returns
startActivityForResult(intent, REQ_CODE_CROP_PHOTO);
}
I hope you got solution but this is for them who still finding for solution.
use this line of code in onActivityResult
Uri imageUri = data.getData();
OR Refer this link for getting URI.
Just use this code of getPath(final Context context, final Uri uri), Using uri you are having it will return path of File.
#SuppressLint("NewApi")
public static 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];
}
// TODO handle non-primary volumes
}
// 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 getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context
* The context.
* #param uri
* The Uri to query.
* #param selection
* (Optional) Filter used in the query.
* #param selectionArgs
* (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
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 column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri
* The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
/**
* #param uri
* The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
/**
* #param uri
* The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
}

Categories

Resources