image attach option is not coming after taking image from camera - android

frnds,on clicking on button i open camera for taking picture ,i take picture successfull and now only two option is coming after clicking pic,"save" and "Discard",there is not any option for attaching the camera clicked image so how to attach image and display image in next view?
my code is ...
public void function2(int id){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST||requestCode == SELECT_PICTURE) {
try{
try{
selectedImageUri = data.getData();
//OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
//DEBUG PURPOSE - you can delete this if you want
if(selectedImagePath!=null){
Intent i=new Intent(MainMenu.this,Imageprview.class);
startActivity(i);
System.out.println(selectedImagePath);
}
else
System.out.println("selectedImagePath is null");
if(filemanagerstring!=null)
System.out.println(filemanagerstring);
else System.out.println("filemanagerstring is null");
//NOW WE HAVE OUR WANTED STRING
if(selectedImagePath!=null)
System.out.println("selectedImagePath is the right one for you!");
else
System.out.println("filemanagerstring is the right one for you!");
}catch (NullPointerException e) {
// TODO: handle exception
} }catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
} }
}
//UPDATED!
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor!=null)
{
//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else return null;
}

Button btnCam=(Button)findViewById(R.id.camBtn);
btnCam.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Intent detailActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class);
//startActivity(detailActivity);
saveImage();
} });
}
public void saveImage()
{
try {
FileOutputStream fos = openFileOutput("MyFile.jpeg", Context.MODE_WORLD_WRITEABLE);
fos.close();
File f = new File(getFilesDir() + File.separator + "MyFile.jpeg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,90);
startActivityForResult(intent,IMAGE_CAPTURE);
//startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)),IMAGE_CAPTURE);
}
catch(IOException e) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_OK){
finish();
//imageView=(ImageView)findViewById(R.id.imageView1);
//imageView.setImageURI(imageUri);
Intent detActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class);
startActivity(detActivity);
//Log.d("ANDRO_CAMERA","Picture taken!!!");
//
}
}
}
IN DETAIL PROFILE ACTIVITY
public class detailProfile extends Activity{
String fname=new File(getFilesDir(),"MyFile.jpeg").getAbsolutePath();
//USING THIS FILE PATH YOU CAN LOAD THE IMAGE IN THIS ACTIVITY
}
YOU HAVE ANOTHER OPTION YOU CAN PASS THE IMAGE TO THROUGH THE INTENT AT THE TIME OF CREATING THE NEW INTENT AND AFTER THAT YOU CAN ACCESS THAT IMAGE THROUGH THE BUNDLE OBJECT IN THE NEW INTENT.
bytes[] imgs = ... // your image
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra("img", imgs);
startActivity(intent)
in detailprofile
bytes[] receiver = getIntent().getExtra("imgs");
//using Byte array you can display your image in ur imageview

There is no such option available.you can save file in to sdcard or any external storage
c the code i have done for saving image in external storage.
public void onClick(View v)
{
if(v == imgForPhotograph) {
path = Environment.getExternalStorageDirectory() + "/photo1.jpg";
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.gc();
if (requestCode == CAPTURE_IMAGE_ACTIVITY) {
if (resultCode == Activity.RESULT_OK) {
try {
// Call function MakeFolder to create folder structure if
// its not created
if(imageBitmap != null) {
imageBitmap = null;
imageBitmap.recycle();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
imageBitmap = BitmapFactory.decodeFile(path, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm
byte[] bmpbyte = baos.toByteArray();
//
Imagebase64= Base64.encodeToString(bmpbyte, Base64.DEFAULT); // set
imgForPhotograph.setImageBitmap(imageBitmap);
isImageTaken = true;
// Name for image
IMAGEPATH = getString(R.string.Image)
+ System.currentTimeMillis();
SaveImageFile(imageBitmap,IMAGEPATH);
} catch (Exception e) {
Toast.makeText(this, "Picture Not taken",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
}
All The Best....

Hi guys, this code is working. For camera and stored into sd card:
public class CampicsaveActivity extends Activity
{
/** Called when the activity is first created. */
FrameLayout frm;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
frm=(FrameLayout)findViewById(R.id.preview);
Button btnCam=(Button)findViewById(R.id.buttonClick);
btnCam.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Intent detailActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class);
// startActivity(detailActivity);
saveImage(0);
} });
}
public void saveImage(int IMAGE_CAPTURE)
{
try
{
FileOutputStream fos = openFileOutput("MyFile.jpeg", Context.MODE_WORLD_WRITEABLE);
fos.close();
File f = new File(getFilesDir() + File.separator + "MyFile.jpeg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,90);
startActivityForResult(intent,IMAGE_CAPTURE);
//startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)),IMAGE_CAPTURE);
}
catch(IOException e)
{;}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 0)
{
if (resultCode == RESULT_OK)
{
finish();
//imageView=(ImageView)findViewById(R.id.imageView1);
//imageView.setImageURI(imageUri);
Intent detActivity = new Intent(getBaseContext(),CampicsaveActivity.class);
startActivity(detActivity);
//Log.d("ANDRO_CAMERA","Picture taken!!!");
//
}
}
}
}
}

Related

Cant load picture

I have a problem when I'm trying to load a picture that saved on the phone.
I have a "Helper class"
public class FileHelper {
public static String saveBitmapToFile(Bitmap bitmap, Context context, String fileName) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// write the compressed bitmap to the outputStream(bytes)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
FileOutputStream fo = null;
try {
fo = context.openFileOutput(fileName, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
Toast.makeText(context, "בעיה ,", Toast.LENGTH_SHORT).show();
}
try {
fo.write(bytes.toByteArray());
fo.close();// close file output
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
}
Here's where I'm trying to upload the photo:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
iv = (ImageView) findViewById(R.id.ivPic);
btnTakePic = (Button) findViewById(R.id.btnpic);
btnPickPicture = (Button) findViewById(R.id.btnpicpic);
try {
bitmap = BitmapFactory.decodeStream(this.openFileInput(PIC_FILE_NAME));
} catch (FileNotFoundException e) {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cam);
}
iv.setImageBitmap(bitmap);
btnTakePic.setOnClickListener(this);
btnPickPicture.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = null;
if (v == btnTakePic) {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
} else if (v == btnPickPicture) {
Intent pickPickIntent = new Intent(Intent.ACTION_PICK);
File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String picDirPath = picDir.getPath();
Uri uData = Uri.parse(picDirPath);
pickPickIntent.setDataAndType(uData, "image/*");
startActivityForResult(pickPickIntent, PICK_PICTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK)
{
bitmap = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bitmap);
FileHelper.saveBitmapToFile(bitmap,getApplicationContext(),PIC_FILE_NAME);
Bitmap bitmapx = iv.getDrawingCache();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("BitmapImage", bitmapx);
} else if (requestCode == PICK_PICTURE) {
if (resultCode == RESULT_OK) {
Uri URI = data.getData();
String[] FILE = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(URI,
FILE, null, null, null);
cursor.moveToFirst();
options = new BitmapFactory.Options();
int columnIndex = cursor.getColumnIndex(FILE[0]);
String ImageDecode = cursor.getString(columnIndex);
cursor.close();
options.inSampleSize = 5;
Bitmap bmp = BitmapFactory.decodeFile(ImageDecode, options);
iv.setImageBitmap(bmp);
FileHelper.saveBitmapToFile(bmp,getApplicationContext(),PIC_FILE_NAME);
Bitmap bitmapx = iv.getDrawingCache();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("BitmapImage", bitmapx);
}
}
}
and Here is where I am trying to load the saved pic:
private void updateHeader()
{
ImageView ivHeader = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.ivHeader);
try{
bitmap= BitmapFactory.decodeStream(this.openFileInput(PIC_FILE_NAME));
ivHeader.setImageBitmap(bitmap);
}
catch (FileNotFoundException e){
Toast.makeText(getApplicationContext(),"error occured",Toast.LENGTH_LONG);
}
}
I have to say that the Toast message is not shown and There are no errors. App not crashing but the pic stays with no change.
Make sure you have external read storage permission. Here is how to request permission.
PS: Also make sure you have added that permission to AndroidManifest.xml

Android Choose Image or Camera

I have implemented the code for choosing an image from SD or Camera.
But, my image doesn't show up in ImageView and I can't choose an image from SD card.
When I click on an image from SD card it jumps instant back to my Activity.
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 which){
if(which == 0){
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),"event_image"+String.valueOf(System.currentTimeMillis()+".jpg"));
imageCaptureUri = Uri.fromFile(file);
try {
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageCaptureUri);
intent.putExtra("return data",true);
startActivityForResult(intent,PICK_FROM_CAMERA);
}catch(Exception ex){
ex.printStackTrace();
}
dialog.cancel();
}else{
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();
mImageView = (ImageView) findViewById(R.id.imageView);
imagePicker = (ImageButton) findViewById(R.id.image_picker);
imagePicker.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dialog.show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode != RESULT_OK)
return;
Bitmap bitmap = null;
String path ="";
if(requestCode == PICK_FROM_FILE) {
imageCaptureUri = data.getData();
path = getRealPathFromURI(imageCaptureUri);
if(path == null)
path = imageCaptureUri.getPath();
if(path != null){
bitmap = BitmapFactory.decodeFile(path);
}
}else{
path = imageCaptureUri.getPath();
bitmap = BitmapFactory.decodeFile(path);
}
mImageView.setImageBitmap(bitmap);
}
public String getRealPathFromURI(Uri contentURI){
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentURI,proj,null,null,null);
if(cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
First you need to use permission WRITE_EXTERNAL_STORAGE in AndroidManifest.xml
In your xml layout :
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="380dp"
android:background="#f241c9" />
<Button
android:id="#+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Take Photo" />
<Button
android:id="#+id/btnPick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Pick Photo" />
In your activity class :
private static final String TAG = "my_log";
private static final int REQUEST_CAPTURE_FROM_CAMERA = 1;
private static final int REQUEST_PICK_FROM_FILE = 2;
private static final int REQUEST_CROP_INTENT = 3;
ImageView img;
Button btnCapture, btnPick;
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.img);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnPick = (Button) findViewById(R.id.btnPick);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_captured.jpg");
// put Uri as extra in intent object
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, REQUEST_CAPTURE_FROM_CAMERA);
}
});
btnPick.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, "Complete action using"), REQUEST_PICK_FROM_FILE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == REQUEST_CAPTURE_FROM_CAMERA) {
try {
cropImage(Uri.fromFile(file));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else if (requestCode == REQUEST_PICK_FROM_FILE) {
try {
cropImage(data.getData());
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else if (requestCode == REQUEST_CROP_INTENT) {
// Create an instance of bundle and get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap from extras
Bitmap bitmap = extras.getParcelable("data");
img.setImageBitmap(bitmap);
if (saveBitmapToStorage(bitmap)) {
Log.d(TAG, "Bitmap saved to file successful.");
} else {
Log.d(TAG, "Failed to save Bitmap to storage.");
}
}
}
public void cropImage(Uri picUri) {
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, REQUEST_CROP_INTENT);
}
private boolean saveBitmapToStorage(Bitmap finalBitmap) {
boolean result = false;
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_cropped.jpg");
Log.d(TAG, "file path = " + file.getAbsolutePath());
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// send Broadcast to notify this photo and see it in Gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

Android "TAKE PHOTO" - Image which is clicked is getting saved as a corrupt image

I have a button, which opens up a dialog box asking user to either "Take Picture" or "Choose from gallery".
I am facing issues when user "Take photo" , image is getting clicked, and for verification purpose I am setting Bitmap image inside the circularImage view, but when I go to specified location path of the image, either Image is not there or Image is corrupted.
Also I am trying to upload the image to the server using AsyncHttpClient in android but not being able to do it successfully.
Everytime I am getting Java Socket TimeOut Exception.
Below is the code for my Camera Intent Activity
public class AddAnUpdateActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.composeEditText = (EditText) findViewById(R.id.composeEditText);
setContentView(R.layout.add_update);
ProfilePictureImage = (CircularImageView) findViewById(R.id.ProfilePic);
insertVideo = (ImageButton) findViewById(R.id.insertVideoButton);
setBtnListenerOrDisable(insertVideo,mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
insertImage = (ImageButton) findViewById(R.id.insertImageButton);
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void setBtnListenerOrDisable(ImageButton btn,
Button.OnClickListener onClickListener,
String intentName) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setClickable(false);
}
}
private boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddAnUpdateActivity.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);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("Assert")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
Log.d("PhotoImage","file path:"+f);
Log.d("PhotoImage","list of file path:"+ Arrays.toString(f.listFiles()));
for (File temp : f.listFiles()) {
if (temp.getName().equals("Image.jpg")) {
Log.w("PhotoImage","enter in if block");
f = temp;
break;
}
}
try {
Log.w("PhotoImage","enter in else block");
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
if(bitmap!=null)
{
bitmap.recycle();
bitmap=null;
}
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Pictures" + File.separator + "Screenshots";
Log.w("PhotoImage","path where the image is stored :"+path);
setFilePath(path);
f.delete();
OutputStream outFile;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
Log.w("PhotoImage","file value:"+String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
setFilePath(picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.d("PhotoImage path of image from gallery......******************.........", picturePath + "");
ProfilePictureImage.setImageBitmap(thumbnail);
}
else if(requestCode == 3){
handleCameraVideo(data) ;
}
}
}
private void handleCameraVideo(Intent data) {
VideoUri = data.getData();
VideoView.setVideoURI(VideoUri);
//mImageBitmap = null;
} }
private void startActivityFeedActivity() {
Intent i = new Intent(getApplicationContext(), ActivityFeedActivity.class);
startActivity(i);
}
}
I simplified your code .keep reference of file path global
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
globalpath =f.getAbsolutePath(); //String make it global
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
//your onactivityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File myfile = new File(globalpath);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(myfile.getAbsolutePath(),
bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Pictures" + File.separator + "Screenshots";
OutputStream outFile;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
myfile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Depending on your Android version and device, the camera intent is to be implemented differently. Check out https://github.com/ralfgehrer/AndroidCameraUtil. The code is tested on 100+ devices.
After take the photo remember to use this:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
to scan the media file in your gallery. If you doesn't do it your photo will appear after some time. You can do it in onClick:
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
}
});

user Intent send image path to another Activity

sometime i running App on my phone.problem is when i click Ok button after camera was pick photo up,at this moment!App' stop running!in fact,i wanna see Pic on another Activity!Is
take picture:
private void takePhoto() {
String SDState = Environment.getExternalStorageState();
if (SDState.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
ContentValues values = new ContentValues();
photoUri = getActivity().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(getActivity(), R.string.take_photo_rem,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getActivity(), R.string.takePhoto_msg,
Toast.LENGTH_LONG).show();
}
}
album:
private void pickPhoto() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
}
onActivityResult: user intent send image uri
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
doPhoto(requestCode, data);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void doPhoto(int requestCode, Intent data) {
if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
if (data == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
photoUri = data.getData();
if (photoUri == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
}
String[] pojo = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(photoUri, pojo, null, null,
null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
try {
if (Integer.parseInt(Build.VERSION.SDK) < 14) {
cursor.close();
}
} catch (Exception e) {
Log.e(TAG, "error:" + e);
}
}
Log.i(TAG, "imagePath = " + picPath);
if (picPath != null) {
Intent startEx = new Intent(getActivity(), PhotoPre.class);
Bundle bundle = new Bundle();
bundle.putString(SAVED_IMAGE_DIR_PATH, picPath);
startEx.putExtras(bundle);
startActivity(startEx);
} else {
Toast.makeText(getActivity(), R.string.photo_err, Toast.LENGTH_LONG)
.show();
}
}
preview image Activity!is getIntent() seted null?
Bundle bundle = getIntent().getExtras();
picPath = bundle.getString(KEY_PHOTO_PATH);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bm = BitmapFactory.decodeFile(picPath, options);
1 - start camera for take image
Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment .getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, Const.dbSrNo + "image.jpg");
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
2 - write below code in "onActivityResult"
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
File imgFile = new File(Environment.getExternalStorageDirectory(),
"/MyImages/");
/*photo = BitmapFactory.decodeFile(imgFile.getAbsolutePath() + "/"
+ Const.dbSrNo + "image.jpg");*/
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
options.inPurgeable=true;
Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath() + "/"
+ Const.dbSrNo + "image.jpg",options);
imageView2.setImageBitmap(bm);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byteImage_photo = baos.toByteArray();
Const.imgbyte=byteImage_photo;
3 - generate one java file Const.java
public class Const {
public static byte[] imgbyte = "";
}
4 - now display that image in your activity using
byte[] mybits=Const.imgbyte;
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(mybits, 0, mybits.length, options);
yourImageview.setImageBitmap(bitmap);

Android camera capture activity returns null Uri

This code worked on samsung before but now that i'm using Nexus One with Android 2.3.6, it's crashing as soon as I take a picture and click ok or choose a photo from gallery. Stacktrace shows a null pointer exception on the Uri.
My code for the activating the camera is as follows:
public void activateCamera(View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == CHOOSE_IMAGE_ACTIVITY_REQUEST_CODE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
&& resultCode == RESULT_OK && null != data) {
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();
Bitmap bits = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
try {
bits = BitmapFactory.decodeStream(new FileInputStream(picturePath),null,options);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any idea what could be the problem?
Thanks!
You have to tell the camera, where to save the picture and remeber the uri yourself:
private Uri mMakePhotoUri;
private File createImageFile() {
// return a File object for your image.
}
private void makePhoto() {
try {
File f = createImageFile();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mMakePhotoUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, REQUEST_MAKE_PHOTO);
} catch (IOException e) {
Log.e(TAG, "IO error", e);
Toast.makeText(getActivity(), R.string.error_writing_image, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_MAKE_PHOTO:
if (resultCode == Activity.RESULT_OK) {
// do something with mMakePhotoUri
}
return;
default: // do nothing
super.onActivityResult(requestCode, resultCode, data);
}
}
You should save the value of mMakePhotoUri over instance states withing onCreate() and onSaveInstanceState().
Inject this extra into the Intent that called onActivityResult and the system will do all the heavy lifting for you.
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
Doing this makes it as easy as this to retrieve the photo as a bitmap.
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
dont pass any extras, just define the path where you have placed or saved the file directly in onActivityResult
public void openCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = createImageFile();
boolean isDirectoryCreated = file.getParentFile().mkdirs();
Log.d("", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);
}
catch (Exception e)
{
}
}
private File createImageFile() {
clearTempImages();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
Date());
File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp +
".jpg");
fileUri = Uri.fromFile(file);
return file;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null ;
if (resultCode == Activity.RESULT_OK ) {
try {
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
bitmap = getBitmap(tempFileUri);
bitmap = getBitmap(data.getData());
} catch (Exception e) {
e.printStackTrace();
}
} else {
getActivity().finish();
}
if (bitmap != null) {
postImagePick(bitmap);
}
}

Categories

Resources