I'm new to android development. I am trying to create an app where when a user take a picture, it's path will be saved to the database. I am able to save and retrieve the image when it's from the gallery, But how do I save it if it's taken by camera?
Here's My Code
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Student_Profile.this);
builder.setTitle("Add Photo");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
0);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == 0) {
studentsDbAdapter.delete_Pic_byID(studID);
Uri targetUri = data.getData();
picture_location=getPath(targetUri);
// picture_location = targetUri.toString();
studentsDbAdapter.insertImagePath(studID ,picture_location);
showpic();
} }
else if (requestCode == 1) {
// How do I get The URI?
// I'm thinking that maybe if I can get the Uri
//from the new image I can save it like how I saved the image to my DB gallery style.
String pic_location=getPath(Uri);
studentsDbAdapter.insertImagePath(studID ,pic_location);
showpic();
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void showpic() {
//LoginDataBaseAdapter db = studentsDbAdapter.open();
boolean emptytab = false;
boolean empty = studentsDbAdapter.checkPic(null, emptytab);
//Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
if(empty==false)
{
String pathName = studentsDbAdapter.getImapath(studID);
File image = new File(pathName);
if(image.exists()){
ImageView imageView= (ImageView) findViewById(R.id.studpic);
imageView.setImageBitmap(BitmapFactory.decodeFile(image.getAbsolutePath()));
}
}
}
Try this. It may help you.
if (fromGallery) {
data.getData()); //get image data like this
} else {
bm = (Bitmap) data.getParcelableExtra("data");
}
Related
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
cameraIntents.add(intent);
}
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI); galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, 1);
So , thats How I call to open either camera or take a picture. How i read them on onactivityresult????check below the code. The problem, when image chosen from photos it works, when taken from camera it works. But when chosen from gallery folder, it doesnt work for some reason. Also some of clients are reporting me problem on sony xperia e4 phones.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK && requestCode == 1
) {
Bitmap bm = null;
try
{
Bundle extras = data.getExtras();
bm = (Bitmap) extras.get("data");
}
catch(Exception e)
{
try
{
Uri selectedImage = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
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();
Common.setBitmap(null);
bm = BitmapFactory.decodeFile(filePath);
BitmapFactory.decodeFile(Common.getRealPathFromURI(data.getData(), rootView.getContext()), bounds);
if(bm == null)
bm = BitmapFactory.decodeFile(Common.getRealPathFromURI(selectedImage, AddStoreActivity.this), options);
if(bm == null)
bm = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
}
catch(Exception e1)
{
}
}
}
} catch (Exception e) {
}
}
public static String getRealPathFromURI(Uri contentURI, Context cont) {
Cursor cursor = cont.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(MediaColumns.DATA);
return cursor.getString(idx);
}
}
This is how I do this and it works:
private void displayAddPhotoDialog() {
final CharSequence[] items = getResources().getStringArray(R.array.photo_dialog_options);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(R.string.photo_dialog_title));
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == TAKE_PHOTO_OPTION) {
dispatchTakePictureIntent();
} else if (item == CHOOSE_FROM_LIBRARY_OPTION) {
dispatchPickImageIntent();
} else if (item == CANCEL_OPTION) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
imageUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_SHORT).show();
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
} else {
Toast.makeText(getActivity(), R.string.no_camera_error_message, Toast.LENGTH_SHORT).show();
}
}
protected void dispatchPickImageIntent() {
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
intent.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
}
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture)), GALLERY_REQUEST_CODE);
}
And your onActivityResult method should look like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
photoReceivedFromCamera = true;
getActivity().getContentResolver().notifyChange(imageUri, null);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(imageUri);
getActivity().sendBroadcast(mediaScanIntent);
//do want you want with the uri(taken photo)
} else if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_CANCELED) {
//The user cancelled the take picture action...
if (!photoReceivedFromCamera) {
//If the user has not previously taken a picture,
//this means he is cancelling the take photo process
onCancelTakePicture();
}
} else if (requestCode == GALLERY_REQUEST_CODE && data != null && data.getData() != null) {
Uri uri = data.getData();
//do want you want with the uri(selected image)
}
}
I have an app with image cropping option. After cropping the actual image, the cropped image is saved in gallery. My question is how to retrieve the file name and path of the cropped image saved in gallery.
my code is,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
Button button = (Button) findViewById(R.id.btn_crop);
mImageView = (ImageView) findViewById(R.id.iv_photo);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
mImageView.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
I have tried a lot but not retrieving the file name and path. Is there any solution.
You are using startActivityForResult(), but do you override onActivityResult()? In your case you need to do the following:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK)
{
Uri pictureUri = data.getData();
}
}
This code gets the Uri of the picture. Then you can use this Uri to get the path, using a method like below:
private 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();
}
}
}
EDIT
After you crop the Bitmap and ready to go, you can save it with something like this:
private Uri saveOutput(Bitmap croppedImage)
{
Uri saveUri = null;
// Saves the image in cache, you may want to modify this to save it to Gallery
File file = new File(getCacheDir(), "cropped");
OutputStream outputStream = null;
try
{
file.getParentFile().mkdirs();
saveUri = Uri.fromFile(file);
outputStream = getContentResolver().openOutputStream(saveUri);
if (outputStream != null)
{
croppedImage.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
}
} catch (IOException e)
{
// log the error
}
return saveUri;
}
After getting the Uri, you can get path to cropped image with the same method above.
Right now I have an imageview. Clicking on the imageview I can get the option to select the gallery/camera intent.selecting on the required intent and the required picture I get the image in the imageview.This works fine for one single image.
How to get more than one picture.I mean the imageview[].Is there any code on this available?
Start Intent with EXTRA_ALLOW_MULTIPLE
Intent intent = new Intent( );
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent,
"select multiple images"), PICK_IMAGE_MULTIPLE);
On receiving side
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK){
if(requestCode == PICK_IMAGE_MULTIPLE){
String[] imagesPath = data.getStringExtra("data").split("\\|");
}
}
}
thanks for the response but here is my code.Now please let me know how to go ahead to have multiple images shown up in multiple imageviews.Also let me know if I need a placeholder like gridview for that?
ImageView image_view = new ImageView(this);
image_view.setId(field_id);
Uri selectedImage = Uri.parse(field_val);
String[] filePath = { MediaStore.Images.Media.DATA };
String picturePath;
Cursor c = getContentResolver().query(selectedImage,
filePath, null, null, null);
c.moveToFirst();
if(c.moveToFirst() && c.getCount() >= 1)
{
int columnIndex = c.getColumnIndex(filePath[0]);
picturePath = c.getString(columnIndex);
c.close();
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
Bitmap thumbnail = (BitmapFactory.decodeFile(
picturePath, bitmapOptions));
image_view.setImageBitmap(thumbnail);
image_view.setTag(selectedImage);
}
else {
image_view.setImageDrawable(getResources().getDrawable(
R.drawable.camera_launcher));
}
image_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getImage();
}
});
private void getImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bundle extras = data.getExtras();
try {
((ImageView) findViewById(R.id.imageid)).setImageBitmap((Bitmap) extras
.get("data"));
((ImageView) findViewById(R.id.imageid))).setTag(R.string.imgtag,
data.getDataString());
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
String picturePath;
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
picturePath = c.getString(columnIndex);
c.close();
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath,
bitmapOptions));
((ImageView) findViewById(R.id.imageid))).setImageBitmap(thumbnail);
((ImageView) findViewById(R.id.imageid))).setTag(R.string.imgtag,
selectedImage.toString());
}
}
}
I have got an app that lets you click on an ImageButton and then brings you to the Android Gallery or the camera. What I am looking for is an onActivityResult method that retrieves the image path from the clicked/ taken image and stores it in a string.
Can someone help me? Here is the onClick method that opens up the Gallery/Camera:
private void showImageDialog() {
final String [] items = new String [] {"From Camera", "From SD Card"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mImageCaptureUri = Uri.fromFile(file);
try {
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
dialog.cancel();
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
dialog.show();
}
Use this code,
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
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();
selectedImagePath = getPath(selectedImageUri);
Log.v("IMAGE PATH====>>>> ",selectedImagePath);
}
}
}
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);
}
}
The selectedImagePath is the path of the image.
I have an activity that retrieves images from the device's gallery and uploads to a service. Now, for optimisation purposes, I would like to avoid uploading images that are on Picasa an just store their ID or URL for later retrieval.
So my question is, how do I retrieve that information. My intent code is pasted below and retrieves the URI of the image.
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(galleryIntent, GALLERY_PIC_REQUEST);
I tried to look for the PICASA_ID (MediaStore.Images.Media.PICASA_ID), but by using the method above, it returns null. Any ideas?
Launch an ACTION_GET_CONTENT intent instead of an ACTION_PICK
Provide a MediaStore.EXTRA_OUTPUT extra with an URI to a temporary file.
Add this to your calling activity:
File yourFile;
Now use this code to get Intent:
yourFile = getFileStreamPath("yourTempFile");
yourFile.getParentFile().mkdirs();
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
galleryIntent .setType("image/*");
galleryIntent .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(yourFile));
galleryIntent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.name());
startActivityForResult(galleryIntent, GALLERY_PIC_REQUEST);
MAKE SURE THAT yourFile is created
Also in your calling activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case GALLERY_PIC_REQUEST:
File file = null;
Uri imageUri = data.getData();
if (imageUri == null || imageUri.toString().length() == 0) {
imageUri = Uri.fromFile(mTempFile);
file = mTempFile;
//this is the file you need! Check it
}
//if the file did not work we try alternative method
if (file == null) {
if (requestCode == 101 && data != null) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
//check this string to extract picasa id
}
}
break;
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor!=null)
{
int index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(index);
}
else return null;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dir =new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyImages");
dir.mkdir();
filename = ("Image_" + String.valueOf(System.currentTimeMillis()) + ".poc");
}
protected Uri getTempFile()
{
File file = new File(dir,filename);
muri = Uri.fromFile(file);
return muri;
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add("Pick Image");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// TODO Auto-generated method stub
super.onOptionsItemSelected(item);
openOptionsChooseDialog();
return true;
}
private void openOptionsChooseDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(AppActivity.this).setTitle("Select Image").setItems(items, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
startActivityForResult(intent, SELECT_PICTURE);
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case SELECT_PICTURE : if (resultCode == RESULT_OK)
{
filepath = muri.getPath();
Toast.makeText(this, filepath, Toast.LENGTH_SHORT).show();
//can do bla bla bla...
}
I have used the same approach and it woks.Hope It could help u too..