URI VS ACTION_GET_CONTENT - android

When to use
// to get image randomly
public static Uri getRandomImage(ContentResolver resolver) {
String[] projection = new String[] { BaseColumns._ID
};
Uri uri = new Random().nextInt(1) == 0 ? Media.EXTERNAL_CONTENT_URI
: Media.INTERNAL_CONTENT_URI;
Cursor cursor = Media.query(resolver, uri, projection, null,
MediaColumns._ID);
if (cursor == null || cursor.getCount() <= 0) {
return null;
}
cursor.moveToPosition(new Random().nextInt(cursor.getCount()));
return Uri.withAppendedPath(uri, cursor.getString(0));
}
and when to use ACTION_GET_CONTENT intent ?
as I want to pick an Image from an android device !
PLease help

If you want to pick an image from teh android gallery then try something like this :
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 100);
and to get back the result you could do something like this :
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
}
}
}
You could also refer to this :
How to pick an image from gallery (SD Card) for my app?

Related

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!.

Retrieve the path of Image from gallery into Edittext

I want to Achieve the following in my project:
open the Gallery on clicking an Edittext.
select an Image or File in the gallery and get its path into my edittext.
Can anyone tell me how to do this?
On your onActivityResult
Uri uri = intent.getData();
And then grap that uri path this way
MyEditText.setText(uri.getPath());
try this,
For open gallary,
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
use this method to get image path,
#SuppressWarnings("unchecked")
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PICK_IMAGE:
String imagepath = (getAbsolutePath(data.getData()) + "|").split("\\|");
break;
}
}
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}

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();
}
}

how to get all images and photos from my android device not from sdcard?

i would like to get all images/photos/wallpapers from my android device with image saved path.
I have implemented code for collect the images from sdcard as follows:
String[] mProjection = {
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA
};
mCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
mProjection,
null,
null,
MediaStore.Images.Media.DEFAULT_SORT_ORDER);
from the above code i can able to retrive the images from sdcard only.But if the images are available in device phone memory then how can i retrive the images/photos/wallpapers?
If i use INTERNAL_CONTENT_URI it is not returning wallapers info other images information
please any body help me....
Try this answer this will work:
public static final int GALLERY_CODE = 322;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(
intent,
"Select Picture"),
GALLERY_CODE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Assinging on corresponding import
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
try {
//add logic for coping file
} catch (Exception e) {
}
}
}
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);
}

Selected Image Not Returned From MediaStore

Based on code suggestions here at stackoverflow, I've tried to extract an image from the MediaStore. However, when I select an actual photo, getContentResolver().query() always returns null. I can't understand why...
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PHOTO);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v(TAG,"onActivityResult: requestCode = "+requestCode+", resultCode = "+requestCode);
if (requestCode == SELECT_PHOTO) {
Uri selectedImage = data.getData();
String[] filePathColumn = {android.provider.MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor != null) {
Log.v(TAG,"onActivityResult: count = "+cursor.getCount());
if (cursor.getCount() == 1) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
Log.v(TAG,"onActivityResult: filePath = "+filePath);
}
cursor.close();
}
}
}
try restart your emulater or your device(or uninstall/install the SD card)?
somebody tell me the Android System will scan the medias when restart or reload SD card...maybe the database hasn't change.

Categories

Resources