Get camera image Inside Iistview - android

I have custom Listview. Inside it has one Button and ImageView.
on Button click Camera will open.(Camera Intent fired).
I want that captured Image (you also call as Bitmap) onto ImageView which is also a ListItem.
that means when i capture image and press Done button of camera then my imageview have to set that image.
How can i do this?

Follow the below steps,
start activity for result of camera intent from your activity.
after capturing picture control callback to onActivityResult of you activity.
handle path of image.
set that path to your image by setting property in your listview item position.

private static int FILE_SELECT_CODE_1 = 0;
function intentCamera(){
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, FILE_SELECT_CODE_1);
}
private String getLastImagePath() {
final String[] imageColumns = { MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
null, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
//int id = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
String fullPath = imageCursor.getString(imageCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
// Log.d(TAG, "getLastImageId::id " + id);
// Log.d(TAG, "getLastImageId::path " + fullPath);
imageCursor.close();
return fullPath;
} else {
return "";
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FILE_SELECT_CODE_1 && resultCode == RESULT_OK){
String lastImagePath = getLastImagePath();
File fileImage = new File(lastImagePath);
Uri u = Uri.fromFile(fileImage);
//now you can set the image example:
ImageView img = new ImageView(this);
img.setImageURI(u);
}
}

Related

Choose an image from gallery and show it using an ImageView

private static int RESULT_LOAD = 1;
String img_Decodable_Str;
ImageView imageView = (ImageView) findViewById(R.id.Gallery);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD);
}
});}
#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 && 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]);
img_Decodable_Str = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.Gallery);
// Set the Image in ImageView after decoding the String
imageView.setImageBitmap(BitmapFactory
.decodeFile(img_Decodable_Str));
} else {
Toast.makeText(this, "Hey pick your image first",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went embrassing", Toast.LENGTH_LONG)
.show();
}
}}
I have an ImageView. If the user clicks on the ImageView he will be able to add an image of his choice to it. When i click on the ImageView I'm redirected to gallery but when i choose an image, that image isn't showing in the ImageView. where have i gone wrong?
In the short term, replace:
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]);
img_Decodable_Str = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.Gallery);
// Set the Image in ImageView after decoding the String
imageView.setImageBitmap(BitmapFactory
.decodeFile(img_Decodable_Str));
with:
Uri selectedImage = data.getData();
imageView.setImageURI(selectedImage);
Later, use an image-loading library, such as Picasso or Glide, as setImageURI() loads the image on the main application thread, which will freeze your UI for as long as that work takes.

android passing image file path to A then to B and finally C acitivity

I'm new to android and to java trying to learn my way in.
Right now I am trying to achieve (A)Select image form gallery (B) show a preview and ( C ) activity is Uploading to server:
Select image form gallery and show a preview: done (achieved) by using below Code
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// call android default gallery
startActivityForResult(intent, PICK_FROM_GALLERY);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode == PICK_FROM_GALLERY) {
if (resultCode == RESULT_OK) {
fileUri = data.getData();
filePath = getRealPathFromURI(getApplicationContext(), fileUri);
Intent imagePreview = new Intent(MainActivity.this, ImagePreview.class);
imagePreview.putExtra("filePath", filePath);
startActivity(imagePreview);
}
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();
}}
}
And In ImagePreview.java
Intent imagePreview = getIntent();
// image or video path that is captured in previous activity
filePath = imagePreview.getStringExtra("filePath");
displayImage(filePath);
private void displayImage(String filePath) {
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(BitmapHelper.decodeSampledBitmap(filePath, 300, 250));
Now According to my understanding, since the filePath is already a string, I should be able it pass it to uploadactivity.java as such
private void upload(){
Intent upload = new Intent(ImagePreview.this, UploadActivity.class);
upload.putExtra("finalImage", filePath);
startActivity(upload);
}
and in uploadactivity.java
Intent upload = getIntent();
// image or video path that is captured in previous activity
finalImage = upload.getStringExtra("finalImage");
By this I can get to UpoloadActivity and upload button is displayed but filePath is not passed.
What am I doing wrong?
You're not using the same key for the extras:
upload.putExtra("finalImage", filePath);
upload.getStringExtra("filePath");
Replace
finalImage = upload.getStringExtra("filePath");
with
finalImage = upload.getStringExtra("finalImage");

onActivityResult returns null data for an Image Capture

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filePath = getOutputMediaFile(FileColumns.MEDIA_TYPE_IMAGE);
File file = new File(filePath);
Uri output = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(i, RETURN_FILE_PATH);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//data is always null here.
//requestCode = RETURN_FILE_PATH;
//resultCode = Activity.RESULT_OK;
}
I checked the values for file and output Uri, both are fine and the captured image actually exists at that location.
But the data returned in onActivityResult is always null even after capturing the image.
EDIT:
I checked this question:
onActivityResult returns with data = null
which says:
Whenever you save an image by passing EXTRAOUTPUT with camera intent
the data parameter inside the onActivityResult always return null. So,
instead of using data to retrieve the image , use the filepath to
retrieve the Bitmap.
and maybe that solution will work for me. But the above code of mine was a working code until now for the same scenario.
According to this post data is null when you pre insert a uri. That means you already defined your output uri here:
i.putExtra(MediaStore.EXTRA_OUTPUT, output);
So when you get a Activity.RESULT_OK; just load the taken photo by its known url.
Try this code this is working for me.
else if(requestCode == Constant.PICK_FROM_CAMERA)
{
if (resultCode == Activity.RESULT_OK)
{
if(data!=null)
{
mImageCaptureUri = data.getData();
//path= mImageCaptureUri.getPath();
try
{
path = getPath(mImageCaptureUri,Wonderlistpage.this); //from Gallery
}
catch(Exception e)
{
path = mImageCaptureUri.getPath();
Log.i("check image attach or not", e.toString());
}
String arr[] = path.split("/");
int i;
String k = null;
for(i=0;i<arr.length;i++)
{
k=arr[i];
}
photoname="_"+String.valueOf(System.currentTimeMillis()) +k;
if(setprofileimage_sendimagewithmessage==1)
{
performCrop(mImageCaptureUri);
}
else
{
loading_details="CAMERA";
new performBackgroundTask33().execute();
}
}
else
{
file1 = new File(Environment.getExternalStorageDirectory(),
String.valueOf(System.currentTimeMillis()) + "_FromCamera.jpg");
Uri mImageCaptureUri = Uri.fromFile(file1);
try
{
path = getPath(mImageCaptureUri,Wonderlistpage.this); //from Gallery
}
catch(Exception e)
{
path = mImageCaptureUri.getPath();
Log.i("check image attach or not", e.toString());
}
String arr[] = path.split("/");
int i;
String k = null;
for(i=0;i<arr.length;i++)
{
k=arr[i];
}
photoname="_"+String.valueOf(System.currentTimeMillis()) +k;
if(setprofileimage_sendimagewithmessage==1)
{
performCrop(mImageCaptureUri);
}
else
{
loading_details="CAMERA";
new performBackgroundTask33().execute();
}
}
//new UploadTask().execute();
}
}
Try following code
{
final String[] imageColumns = { MediaStore.Images.Media._ID,MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
imageCursor.moveToFirst();
do {
String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
if (fullPath.contains("DCIM")) {
//get bitmap from fullpath here.
return;
}
}
while (imageCursor.moveToNext());
Just Put this code into your onActivityResult. The same problem i have faced on some devices and this solved my problem. Hope this will also help you.
try {
Uri selectedImage = output;
if (selectedImage == null)
return;
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();
} catch (Exception e) {
return;
}
You will get the Picture path in picturePath variable and Uri in selectedImage Variable.
If your activity has launchmode as singleInstance in your manifest then you would face this issue. Try changing it. As it cancels the result everytime.

Start Activity not working properly in this scenario?

Hi every one in the below code after the image has been selected it is not moving to next activity ,in gallery if we select first item it remains in the same activity but we select another item other than first position image it is moving to next activity
startActivity(mv); the shown startactvity is not calling when we click on the first position image
but the toast is appearing as image has been selected but not moving to next activty
public boolean onTouch(View v, MotionEvent arg1) {
// TODO Auto-generated method stub
case R.id.imageView2:
upLoadPhoto();
break;
protected void upLoadPhoto() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("return-data", true);
startActivityForResult(intent, 100);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && data != null && data.getData() != null) {
System.out.println("in case");
Uri _uri = data.getData();
if (_uri != null) {
// User had pick an image.
Cursor cursor = getContentResolver()
.query(_uri,
new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
null, null, null);
cursor.moveToFirst();
// Link to the image
final String imageFilePath = cursor.getString(0);
Log.v("imageFilePath", imageFilePath);
File photos = new File(imageFilePath);
try {
gbmp = BitmapFactory.decodeStream(
new FileInputStream(photos), null, null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cursor.close();
}
mv = new Intent(Imageselection.this, Modeselection.class);
mv.putExtra("test", gbmp);
mv.putExtra("name", 100);
System.out.println("going to gamestart class");
startActivity(mv);
Toast.makeText(getApplicationContext(), "Image selected", Toast.LENGTH_SHORT).show();
}
Its because you passed the whole image to the bundle.
The bundle has limited Size, you cannnot put the image itself into the intent.
You need to save your image to a cache, then either pass the image's file name or file path to the putExtra and then retrieve it later by accessing the filename or file path.
For your case, you select an image from gallery, then you can get the URI or path of that image, put the URI/path to the intent, and retrieve it on your another activity.
When you call an intent to launch the gallery, it will return with data which contains the selected file's Uri.
Here r some sample code you may need if you launch the default gallery:
// Launch Gallery to choose pic.
Intent intentLaunchGallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intentLaunchGallery, LOAD_IMAGE_ACTIVITY_REQUEST_CODE);
...
private String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
...
// Gallery launched to choose picture
if (requestCode == LOAD_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
fileUri = data.getData();
filePath = getPath(fileUri);
// fileUri = Uri.parse(filePath);
// call media scanner to refresh gallery
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{filePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.i("MediaScanner", "Scanned " + path + ":");
Log.i("MediaScanner", "-> uri=" + uri);
}
});
// Toast.makeText(this, "Image chosen from: " + filePath, Toast.LENGTH_LONG).show();
Log.d("MainMenu->onActivityResult", "Image chosen from: " + filePath);
// display the picture chosen by user
Intent intentShowMarkers = new Intent(MainMenuActivity.this, ShowMarkersActivity.class);
intentShowMarkers.putExtra("IMG", filePath);
intentShowMarkers.putExtra("FLAG", false);
MainMenuActivity.this.startActivity(intentShowMarkers);
} else if (resultCode == RESULT_CANCELED) {
// user pressed the cancel of gallery
Toast.makeText(MainMenuActivity.this, "Cancelled.", Toast.LENGTH_SHORT).show();
}
}
try below code. for select an image from gallary
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]);
filePath = cursor.getString(columnIndex);
cursor.close();
and in your onActivityResult method write below intent to go for next activity
Intent picIntent = new Intent(CurrentActivity.this,
NextActivity.class);
picIntent.putExtra("gallery", filePath);
startActivity(picIntent);
in your NextActivity class onCreate Method write below code
ImageView imageView = (ImageView)findViewById(R.id.imgView);
String fileString = getIntent().getStringExtra("gallery");
imageView.setImageBitmap(BitmapFactory.decodeFile(fileString));

take picture from camera and choose from gallery and display in Image view

I want to take photos from gallery and set it in my ImageView as well as I want to take photo from camera and set it into my same Image View.
I am very much stuck on this.
Can anyone help me?
Thanks.
You can handle your camera view click this way:
cameraImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
});
Do this in your activity when you return after capturing image.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0)
{
if(data != null)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
photo = Bitmap.createScaledBitmap(photo, 80, 80, false);
imageView.setImageBitmap(photo);
}
else{
}
}
}
Get the open source code for gallery. Lookout onclick for the image selection. Launch your activity by setting the intent uri being genrated on th onclick .
In your application, get the intent data and get the real path from uri and then decode, set it as image view element .
private String getRealPathFromURI(Uri contentUri) {
int columnIndex = 0;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
try {
columnIndex = cursor.getColumnIndexOrThrow
(MediaStore.Images.Media.DATA);
} catch (Exception e) {
Toast.makeText(ImageEditor.this, "Exception in getRealPathFromURI",
Toast.LENGTH_SHORT).show();
finish();
return null;
}
cursor.moveToFirst();
return cursor.getString(columnIndex);
}
You must implement this code to take image from camera or gallery :
Take this variable :
AlertDialog dialog;
private static final int IMAGE_PICK = 1;
private static final int IMAGE_CAPTURE = 2;
private Bitmap profile_imageBitmap;
On Button click event :
if (v == btn_uploadPhoto) {
dialog.show();
}
Then in your activity's oncreate method :
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) {
if (item == 0) {
path = "";
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
File folder = new File(Environment
.getExternalStorageDirectory() + "/LoadImg");
if (!folder.exists()) {
folder.mkdir();
}
final Calendar c = Calendar.getInstance();
String new_Date = c.get(Calendar.DAY_OF_MONTH) + "-"
+ ((c.get(Calendar.MONTH)) + 1) + "-"
+ c.get(Calendar.YEAR) + " " + c.get(Calendar.HOUR)
+ "-" + c.get(Calendar.MINUTE) + "-"
+ c.get(Calendar.SECOND);
path = String.format(
Environment.getExternalStorageDirectory()
+ "/LoadImg/%s.png", "LoadImg(" + new_Date
+ ")");
File photo = new File(path);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
startActivityForResult(intent, 2);
} else { // pick from file
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Choose a Photo"),
IMAGE_PICK);
}
}
});
dialog = builder.create();
Now Out of Oncreate :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK
|| requestCode == IMAGE_CAPTURE) {
switch (requestCode) {
case IMAGE_PICK:
this.imageFromGallery(resultCode, data);
img_myProfile.setImageBitmap(null);
img_myProfile.setImageBitmap(setphoto);
break;
case IMAGE_CAPTURE:
this.imageFromGallery(resultCode, data);
img_myProfile.setImageBitmap(null);
img_myProfile.setImageBitmap(setphoto);
break;
default:
break;
}
}
}
private void imageFromGallery(int resultCode, Intent 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]);
profile_Path = cursor.getString(columnIndex);
cursor.close();
setphoto = BitmapFactory.decodeFile(profile_Path);
}
private void imageFromCamera(int resultCode, Intent data) {
updateImageView((Bitmap) data.getExtras().get("data"));
}
private void updateImageView(Bitmap newImage) {
setphoto = newImage.copy(Bitmap.Config.ARGB_8888, true);
}
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);
}

Categories

Resources