Take image from Gallery to ImageView in Android - android

I try to display a Image from Gallery to ImageView
This is my Code so far:
public void onClick(DialogInterface dialog, int which) {
pictureActionIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pictureActionIntent.setType("image/*");
pictureActionIntent.putExtra("return-data", true);
startActivityForResult(pictureActionIntent, GALLERY_PICTURE);
}
if (resultCode == RESULT_OK && null != data) {
Uri selectedImageUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
taskImage = (ImageView) findViewById(R.id.taskPhotoImage);
taskImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
But there is nothing displayed. Just blank a ImageView.
Where is my mistake? I've read so many tutorials. But all of them shows the same solution.
Kind Regards!

you can use the below code. it works for me.
mainactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center" >
<ImageView
android:id="#+id/imgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center" >
</ImageView>
<Button
android:id="#+id/buttonLoadPicture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0"
android:onClick="loadImagefromGallery"
android:text="Load Picture" >
</Button>
</LinearLayout>
Mainactivity.java
public class MainActivity extends ActionBarActivity {
private static int RESULT_LOAD_IMG = 1;
String image_str,res,imgDecodableString,the_string_response;
Bitmap img;
Exception e;
int contentLength;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadImagefromGallery(View view) {
//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);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
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.imgView);
// Set the Image in ImageView after decoding the String
img = Bitmap.createScaledBitmap(BitmapFactory
.decodeFile(imgDecodableString), 500, 500, false);
imgView.setImageBitmap(img);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
}

Here is code i have used. use it according to your need
private static final int GALLERY_PHOTO = 111;
private void pickImage(){
Intent chooserIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
chooserIntent.setType("image/*");
startActivityForResult(chooserIntent, GALLERY_PHOTO);
}
in your onActivityResult() you should use like this.
if (resultCode == GALLERY_PHOTO && data.getData() != null) {
String filePath = GetFilePathFromDevice.getPath(YourActivityName.this, data.getData());
taskImage = (ImageView) findViewById(R.id.taskPhotoImage);
taskImage.setImageBitmap(BitmapFactory.decodeFile(filePath));
}
Here is class used for getting file path from URI.
#SuppressLint("NewApi")
public final class GetFilePathFromDevice {
/**
* Get file path from URI
*
* #param context context of Activity
* #param uri uri of file
* #return path of given URI
*/
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];
}
}
// 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 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;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}

Related

Hold the image on the Activity

I use this code to pick an image from the device but when the activity is closed the image disappears. How to save it so whenever I open the Activity the image is still there?
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (resultCode == RESULT_OK && data!= null) {
Uri imageData = data.getData() ;
imageView.setImageURI(imageData);
}
}
}
So what you need is save the selected imageUri in local preferences of the activity.
Please check the code below:
public class Prefs {
private static Prefs INSTANCE;
private static SharedPreferences prefs;
public static Prefs getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new Prefs();
prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
}
return INSTANCE;
}
public void setImage(String image) {
prefs.edit().putString("image", image).apply();
}
public String getImage() {
return prefs.getString("image", "");
}
Then in your activity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
if(!TextUtils.isEmpty(Prefs.getInstance(applicationContext).getImage()){
val imgFile = File(Prefs.getInstance(getApl).getImage())
if (imgFile.exists()) {
val myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath())
imageView.setImageBitmap(myBitmap)
}
}
In your onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (resultCode == RESULT_OK && data!= null) {
Uri imageData = data.getData() ;
imageView.setImageURI(imageData);
Prefs.getInstance(applicationContext).setImage(PathUtils.getPath(applicationContext,imageData));
}
}
}
public class PathUtils {
public static String getPath(final Context context, final Uri uri) {
// DocumentProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {// ExternalStorageProvider
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
String storageDefinition;
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
if (Environment.isExternalStorageRemovable()) {
storageDefinition = "EXTERNAL_STORAGE";
} else {
storageDefinition = "SECONDARY_STORAGE";
}
return System.getenv(storageDefinition) + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {// DownloadsProvider
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);
} else if (isMediaDocument(uri)) {// MediaProvider
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);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore (and general)
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
return uri.getPath();
}
return null;
}
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;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
first, you must use cursor for catch media path, then you can store on the hawk or shared preferences with a special key. then open the image with data stored in Hawk or shared preferences.
eg :
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]);
mediaPath = cursor.getString(columnIndex);
Hawk.put("image",mediaPath);
//after_reset =>
String mediaPath1 = Hawk.get("image").toString();
channelImage.setImageBitmap(BitmapFactory.decodeFile(mediaPath1));

Camera intent issue with different phones android

I am calling camera intent to capture an image and get the image uri in onActivtyResult in my fragment.
this is my captureImage()
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA_STORAGE);
}
this is my onActivityResult in fragment
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CAMERA_STORAGE && resultCode == RESULT_OK) {
Uri targetUri = data.getData();
String imagePath;
if (data.toString().contains(AppConstants.CONTENT)) {
imagePath = getRealPathFromURI(targetUri);
} else if (data.toString().contains(AppConstants.CONTENT)) {
imagePath = targetUri.getPath();
} else {
imagePath = null;
}
Log.d("imageuri",imagePath);
}
this getRealPathFromUri()
public String getRealPathFromURI(Uri uri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(uri, proj, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
this works fine in one phone and in some phones, in onActivityResult data.getData() returns null.
to resolve this i came across this Capture Image from Camera and Display in Activity
but here it returns a thumbnail image.
So is there any work around to get the captured image uri from camera.
Try This
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
Write below method to get real path
public static String getRealPath(Context context, Uri uri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
String id = DocumentsContract.getDocumentId(uri);
Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(uri)) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
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;
}
String selection = "_id=?";
String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
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 String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
String column = "_data";
String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
Try this in onActivityResult()
Uri imageUri = data.getData ();
and then you can set it to imageview

How to get an image from the gallery, get its name, save it in the internal memory and get the route of that image

(I apologize if I make mistakes writing in English)
I need to do the same as the title says
I only know how to get the image from the gallery. I think this is correct:
(If it is wrong or it is inefficient please let me know)
private final int SELECT_PICTURE = 200;
btnAddImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galeryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galeryIntent.setType("image/*");
startActivityForResult(galeryIntent.createChooser(galeryIntent, "Sececiona Imagen"), SELECT_PICTURE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case (SELECT_PICTURE):
if(requestCode == RESULT_OK){
Uri path = data.getData();
}
}
break;
}
}
But I don't know how to get the name of the image that I caught from the gallery and save it whit that name in the internal memory of my app.
Then I need the route of the image like "MyAPP/media/ ..." , I don't know the correct name in English for that, and save it in my database (save it in my database is easy) and then use it in my project
I know this is a long message but I need your help because in the Spanish forum of StackOverflow anybody answered me.
onActivityResult :
String path = getPath(getApplicationContext(), data.getData());
File mFile = new File(id);
mFile.getName();
That is the way that a got the name of the file.
And the getPath :
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Log.d("Lucas","TYPE => "+type);
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} 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);
} 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);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
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;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}

Android- Not able to select file from internal storage

I have to get image from internal storage of mobile device and upload to server. If I select image from sdcard it working fine, while if I select image from internal storage it show error, I am not able to get this error.
Here is logcat output -
07-26 10:32:24.868: W/System.err(24051): java.io.FileNotFoundException: /document/primary:Pictures/Screenshots/Screenshot_20160712-172722.png: open failed: ENOENT (No such file or directory)
I am using this code to get image
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
1);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
OnActivityResult code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// 1
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
try {
// SDK < API11
if (Build.VERSION.SDK_INT < 11)
realPath_1 = RealPathUtil
.getRealPathFromURI_BelowAPI11(getActivity(),
data.getData());
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
realPath_1 = RealPathUtil.getRealPathFromURI_API11to18(
getActivity(), data.getData());
// SDK > 19 (Android 4.4)
else
realPath_1 = RealPathUtil.getRealPathFromURI_API19(
getActivity(), data.getData());
Log.e("", "Build Version : " + Build.VERSION.SDK_INT);
Log.e("", "Get Data Get Path : " + data.getData().getPath());
if (realPath_1.equalsIgnoreCase("")) {
realPath_1 = data.getData().getPath().toString();
}
Log.e("", "Real Path 1 : " + realPath_1);
file_1 = realPath_1.substring(
realPath_1.lastIndexOf('/') + 1,
realPath_1.length());
Log.i("File Name 1 ", file_1);
txt_file_name_1.setText(file_1);
} catch (Exception e) {
Uri selected = data.getData();
realPath_1 = selected.getPath();
file_1 = realPath_1.substring(
realPath_1.lastIndexOf('/') + 1,
realPath_1.length());
Log.i("File Name 1 ", file_1);
txt_file_name_1.setText(file_1);
}
}
}}
Here is class named - RealPathUtil to get path of images.
My
android:minSdkVersion="14"
android:targetSdkVersion="23"
and called this method from class RealPathUtil
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;
}
Please help and thanks in advance.
Try this:
boolean isKitKat = false;
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
Code for show file chooser function
private void showFileChooser() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
isKitKat = true;
startActivityForResult(Intent.createChooser(intent, "Select file"), 1);
} else {
isKitKat = false;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select file"), 1);
}
}
OnActivity Result code :
#TargetApi(19)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (data != null && data.getData() != null && resultCode == getActivity().RESULT_OK) {
boolean isImageFromGoogleDrive = false;
Uri uri = data.getData();
if (isKitKat && DocumentsContract.isDocumentUri(getActivity(), uri)) {
if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
realPath_1 = Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
Pattern DIR_SEPORATOR = Pattern.compile("/");
Set<String> rv = new HashSet<>();
String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
if (TextUtils.isEmpty(rawExternalStorage)) {
rv.add("/storage/sdcard0");
} else {
rv.add(rawExternalStorage);
}
} else {
String rawUserId;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
rawUserId = "";
} else {
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
String[] folders = DIR_SEPORATOR.split(path);
String lastFolder = folders[folders.length - 1];
boolean isDigit = false;
try {
Integer.valueOf(lastFolder);
isDigit = true;
} catch (NumberFormatException ignored) {
}
rawUserId = isDigit ? lastFolder : "";
}
if (TextUtils.isEmpty(rawUserId)) {
rv.add(rawEmulatedStorageTarget);
} else {
rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
}
}
if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
Collections.addAll(rv, rawSecondaryStorages);
}
String[] temp = rv.toArray(new String[rv.size()]);
for (int i = 0; i < temp.length; i++) {
File tempf = new File(temp[i] + "/" + split[1]);
if (tempf.exists()) {
realPath_1 = temp[i] + "/" + split[1];
}
}
}
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
String id = DocumentsContract.getDocumentId(uri);
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
Cursor cursor = null;
String column = "_data";
String[] projection = {column};
try {
cursor = getActivity().getContentResolver().query(contentUri, projection, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(column);
realPath_1 = cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
} else if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
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;
}
String selection = "_id=?";
String[] selectionArgs = new String[]{split[1]};
Cursor cursor = null;
String column = "_data";
String[] projection = {column};
try {
cursor = getActivity().getContentResolver().query(contentUri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(column);
realPath_1 = cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
} else if ("com.google.android.apps.docs.storage".equals(uri.getAuthority())) {
isImageFromGoogleDrive = true;
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
Cursor cursor = null;
String column = "_data";
String[] projection = {column};
try {
cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(column);
realPath_1 = cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
realPath_1 = uri.getPath();
}
try {
Log.d(TAG, "Real Path 1 : " + realPath_1);
file_1 = realPath_1.substring(realPath_1.lastIndexOf('/') + 1, realPath_1.length());
Log.i("File Name 1 ", file_1);
} catch (Exception e) {
e.printStackTrace();
}
}
}}
Here file_1 = get image name and realPath_1 show full path of image from internal or external storage.
Happy to help :)
Use bellow code for get file URL.
public static String getPath(final Context context, final Uri uri) {
// check here to KITKAT or new version
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;
}
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;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
Your code looks fine you just have to get runtime permissions from user. In Andorid 6.0 or later needs permission from user at runtime only declaring them manifest is not enough.
See here my earlier post about how to get runtime permissions.
Update:
private void showFileChooser() {
try {
// Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// startActivityForResult(i, RESULT_LOAD_IMAGE);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, RESULT_LOAD_IMAGE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
//Uri selectedImage = data.getData();
txt_file_name_1.setText(data.getData().toString());
}
}

Android (Java) - If i select a picture from gallery app crash

Sry for my bad english, im from germany.
I've developing a Android App and if i select a picture from gallery is the app crash.
On old devices (4.0.2) its works fine but on galaxy s4 its not work.
in logcat i cant see logs.
my code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == IMAGE_UPLOAD && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(getApplicationContext(), selectedImageUri);
uploadItem.setVisible(true);
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if(isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
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];
}
} 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);
} 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);
}
} else if("content".equalsIgnoreCase(uri.getScheme())) {
if(isGooglePhotosUri(uri)) return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
} else if("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
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;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}

Categories

Resources