Getting Image from gallery in android - android

I've been trying to get an image from gallery in this app and then on a button click I want to upload to my PHP server.
The "selectedImagePath" comes as null why?
If anyone has a solutions please help me! Thanks in advance.
onCreate()
img = (ImageView) findViewById(R.id.ImageView01);
Button browse = (Button) findViewById(R.id.Button01);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
});
onActivityResult()
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
selectedImageUri = data.getData();
System.out.println(selectedImageUri);
selectedImagePath = getPath(selectedImageUri);//returns as null
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
getPath()
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

try this
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == Activity.RESULT_OK && data != null){
String realPath;
// SDK < API11
if (Build.VERSION.SDK_INT < 11) {
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
}
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19) {
realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
}
// SDK > 19 (Android 4.4)
else {
realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
}
System.out.println("Image Path : " + realPath);
}
}
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
the code for getRealPath class is not mine, I din't write down the website.

When you get the data, create file from that path first and then get that file's path as "selectedImagePath". Then you will get actual path of image on external storage: Try below code:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
selectedImageUri = data.getData();
File myFile = new File(selectedImageUri);
System.out.println(selectedImageUri);
selectedImagePath = myFile.getPath();
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}

try this code,
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

Try below code
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri uri = data.getData();
String[] filepath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, filepath, null,
null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filepath[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
System.out.println("Image Path : " + filePath);
}

I've spent some time on this problem and eventually I found the fully working solution().
A.
It's taken from cordova-plugin-camera which can be found here:
public static String getRealPath(final Uri uri, final Context context) {
String realPath = null;
if (Build.VERSION.SDK_INT < 11) {
realPath = FileHelper.getRealPathFromURI_BelowAPI11(context, uri);
// SDK >= 11
} else {
realPath = FileHelper.getRealPathFromURI_API11_And_Above(context, uri);
}
return realPath;
}
both methods are provided in [FileHelper.class]:
https://github.com/apache/cordova-plugin-camera/blob/06d609cfa4871b4a2811f5a8f7f0a822733209b9/src/android/FileHelper.java
I don't want to duplicate the code, links are provided instead because solutions are quite complex. /I consider the fact that they could expire but hoping they won't/
B.
Here is a link to the source code of a sample project [RealPathUtil.java]: https://github.com/hmkcode/Android/blob/master/android-show-image-and-path/src/com/hmkcode/android/image/RealPathUtil.java
C.
Another question in here that didn't find much attention. [Stack Overflow Post]: https://stackoverflow.com/a/36714242

Related

how to select image from Device and it's path in android Studio

I need to select image from device and it's full path
But I get null value.. this is my Code
any suggestions
private void openPicture() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
Toast.makeText(this, ""+selectedImagePath, Toast.LENGTH_SHORT).show();
}
}
}
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();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
return uri.getPath();
}
it's return Null value. I need selected image Path.

Image path null in Android

I have code like this, the problem is when i want to save it to sqlite, the error message shown that i got null in image path.
Here is the main activity
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
System.out.println("Data Image : "+selectedImageUri);
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
image1.setVisibility(View.VISIBLE);
image1.setImageURI(selectedImageUri);
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I use this method to take photos from camera.
private void capturePhoto() {
// save this Uri in a field variable.
uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, CAMERA_REQUEST);
}
then onActivityResult will look like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
// use the field Uri, it now points to the path to the image taken from the camera.
}
}
In manifest file set permission
Check permission granted in onActivityResult method and after its granted READ_EXTERNAL_STORAGE
If it has Permission then call doCreatePath() and set the same in onRequestPermissionsResult on permission granted.
void doCreatePath()
{
try {
Uri originalUri = filePath;
String pathsegment[] = originalUri.getLastPathSegment().split(":");
String id = pathsegment[0];
final String[] imageColumns = {MediaStore.Images.Media.DATA};
final String imageOrderBy = null;
Uri uri = getUri();
Cursor imageCursor = getActivity().getContentResolver().query(uri, imageColumns,
null, null, null);
if (imageCursor.moveToFirst()) {
int column_index_data = imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
realPath = imageCursor.getString(column_index_data);
System.out.print("value" + realPath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
It works!.

Select image from gallery for some device it null

i am getting image from gallery from below code
Uri filePath = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.MIME_TYPE};
Cursor cursor =
mCon.getContentResolver().query(filePath, filePathColumn, null, null, null);
but when i select image from file explore in some devices cursor is always null but if i select same image from gallery app it works... why it so ?
try this code
private String uriToFilename(Uri uri) {
String path = null;
if (Build.VERSION.SDK_INT < 11) {
path = RealPathUtil.getRealPathFromURI_BelowAPI11(this, uri);
} else if (Build.VERSION.SDK_INT < 19) {
path = RealPathUtil.getRealPathFromURI_API11to18(this, uri);
} else {
path = RealPathUtil.getRealPathFromURI_API19(this, uri);
}
return path;
}
create RealOathUtil.java
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri) {
Log.e("uri", uri.getPath());
String filePath = "";
if (DocumentsContract.isDocumentUri(context, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
Log.e("wholeID", wholeID);
// Split at colon, use second item in the array
String[] splits = wholeID.split(":");
if (splits.length == 2) {
String id = splits[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();
}
} else {
filePath = uri.getPath();
}
return filePath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Now in onactivtyResult() use this
Uri selectedImageUri = data.getData();
String selectedImagePath = uriToFilename(selectedImageUri);
You should try this.
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Try this code.
To open gallery:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
mImagePath = getPath(selectedImageUri);
mBitmap = BitmapFactory.decodeFile(mImagePath);
mProfilePic.setImageBitmap(mBitmap);
}
}
To get actual path of image:
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Hope this may help you.

How to get any File Path ,Name ,Extension from onActivityResult?

My Codes are:
1.
File file = new File(Environment.getExternalStorageDirectory(),"myFolder");
Log.d("path", file.toString());
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(file), "*/*");
startActivityForResult(intent,0);
2.
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent FileReturnedIntent) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, FileReturnedIntent);
How to get the file path,name,extension? (suppose files are in doc,pdf,csv format)
It return the file extention like pdf, doc .. etc
public static String getMimeType(Context context, Uri uri) {
String extension;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
final MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
} else {
extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
}
return extension;
}
It returns you the real path where you get the file name. One friend use this way and it is really useful.
Get filename and path from URI from mediastore
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
You get file name from this
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
I am late but it can help others here is the solution.
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
String mime = cr.getType(uri);
you can use like this
#Override
public 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();
}
}
Once try as follows if the FileReturnedIntent contains File as extras
Bundle data1=FileReturnedIntent.getExtras();
File f=(File)data1.get(key);
String path=f.getAbsolutePath();
System.out.println("The file path along with extension is : "+path);
Hope this will helps you.
Nova day in Kotlin:
val myFile = File(data?.data!!.path)
you can put String Extra to intent using
intent.putExtra("path", your_path);
and get it in onActivityResult by
FileReturnedIntent.getStringExtra("path");

How to select video from gallery and set the selected video icon to ImageView

This technique is successfully performed for using pictures from Gallery
But i want to implement the same thing for Audio as well as video .
The code is
public void video(View v)
{
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
RESULT_LOAD_VIDEO = 1;
startActivityForResult(i, RESULT_LOAD_VIDEO);
}
public void audio(View v)
{
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
RESULT_LOAD_AUDIO = 1;
startActivityForResult(i, RESULT_LOAD_AUDIO);
}
#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(); String[]
filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex); cursor.close();
// String picturePath contains the path of selected Image
NewPoll.flag++;
Path.patha= picturePath;
Intent ints=new Intent(getApplicationContext(),NewPoll.class);
ints.putExtra("address",picturePath);
ints.putExtra("option",comingData);
startActivity(ints);
}
if (requestCode == RESULT_LOAD_VIDEO && resultCode == RESULT_OK &&null != data)
{
Uri selectedVideo= data.getData(); String[]
filePathColumn = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(selectedVideo,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String videoPath = cursor.getString(columnIndex); cursor.close();
// String picturePath contains the path of selected Image
NewPoll.flag++;
Path.patha= videoPath;
Intent ints=new Intent(getApplicationContext(),NewPoll.class);
ints.putExtra("address",videoPath);
ints.putExtra("option",comingData);
startActivity(ints);
}
if (requestCode == RESULT_LOAD_AUDIO && resultCode == RESULT_OK &&null != data)
{
Uri selectedAudio= data.getData(); String[]
filePathColumn = { MediaStore.Audio.Media.DATA };
Cursor cursor = getContentResolver().query(selectedAudio,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String audioPath = cursor.getString(columnIndex); cursor.close();
// String picturePath contains the path of selected Image
NewPoll.flag++;
Path.patha= audioPath;
Intent ints=new Intent(getApplicationContext(),NewPoll.class);
ints.putExtra("address",audioPath);
ints.putExtra("option",comingData);
startActivity(ints);
}
}
I got success for photo-gallery but dont know how to use video and audio gallery
Code from ur side is appriciated !
Thanks
//from this u get all audio
private void getallaudio()
{
String[] STAR = { "*" };
Cursor audioCursor = ((Activity) cntx).managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
if (audioCursor != null)
{
if (audioCursor.moveToFirst())
{
do
{
String path = audioCursor.getString(audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
controller.audioWrapper.add(new MediaWrapper(new File(path).getName(), path, "Audio",false,color_string));
// Log.i("Audio Path",path);
}while (audioCursor.moveToNext());
}
// audioCursor.close();
}
}
//from this u get all video
private void getallvideo()
{
String[] STAR = { "*" };
controller.videoWrapper.clear();
Cursor videoCursor = ((Activity) cntx).managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
if (videoCursor != null)
{
if (videoCursor.moveToFirst())
{
do
{
String path = videoCursor.getString(videoCursor.getColumnIndex(MediaStore.Images.Media.DATA));
controller.videoWrapper.add(new MediaWrapper(new File(path).getName(), path, "Video",false,color_string));
// Log.i("Video Path",path);
}while (videoCursor.moveToNext());
}
// videoCursor.close();
}
}

Categories

Resources