not getting the values of intent in android - android

i m trying to capture an image, but
onActivityResult(int requestCode, int resultCode, Intent data)
when calling this fun. the intent part is null,
but in
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
i've got the intent = Intent { act=android.media.action.IMAGE_CAPTURE (has extras) }
my code is
public class MainActivity extends Activity {
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
//private static final int RESULT_OK = -1;
private static final int MEDIA_TYPE_IMAGE = 1;
public static String s = null;
private Uri fileUri;
private static Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create Intent to take a picture and return control to the calling application
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
//onActivityResult(CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE, int resultCode, intent)
}
private Uri getOutputMediaFileUri(int type) {
// TODO Auto-generated method stub
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
#SuppressLint("SimpleDateFormat")
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("IWMP-Images", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
// Main Thing here.. data.getData = null coz data = null
Toast.makeText(this, "Image saved to:\n" + data.getData(),Toast.LENGTH_LONG).show();
//s =data.getData().toString();
Intent intent2 = new Intent(MainActivity.this,MainActivity2.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent2);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
Toast.makeText(this, "Image NOT saved ", Toast.LENGTH_LONG).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Related

onActivityResult resultCode always 0 when using camera

So i have 2 Activities, the first one is to launch camera before the second Activity start. After taking the camera, the ImageView on second Activities will changed by the photo ive taken. And if i click the ImageView, it will intent the camera and replacing the image from camera. However, i cant replace the image at ImageView and the resultCode always 0 everytime after taking picture.
here is first Activity
#OnClick(R.id.fab_toko)
private void create_ticket() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(Consts.MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
startActivityForResult(intent, Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
//return FileProvider.getUriForFile(MainActivity.this, MainActivity.this.getApplicationContext().getPackageName(), getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Consts.IMAGE_DIRECTORY_NAME);
//Creating an internal dir;
File mDir = RumahkeduaApplication.getContext().getDir("ISS", Context.MODE_PRIVATE);
//Internal Storage
// File mediaInternalDir = new File(mDir,Consts.IMAGE_DIRECTORY_NAME);
File mediaInternalDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
// Create the storage directory if it does not exist
if (!mediaInternalDir.exists()) {
if (!mediaInternalDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Consts.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == Consts.MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaInternalDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
comImage.compressImage(fileUri.toString());
Intent mainIntent = new Intent(MainActivity.this, CreateTicketActivity.class);
mainIntent.putExtra("id_user", login_user.getId_user());
mainIntent.putExtra("string_uri", fileUri.toString());
mainIntent.putExtra("ticket_type", "Toko Prima");
MainActivity.this.startActivity(mainIntent);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
And here is second Activity
#OnClick(R.id.iv_post_photo)
private void captureImage() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
// if (!ticket_type.equals("Toko Prima")){
// TODO
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(Consts.MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
// start the image capture Intent
startActivityForResult(intent, Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
setResult(RESULT_OK);
// }
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Consts.IMAGE_DIRECTORY_NAME);
File mediaInternalDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
// Create the storage directory if it does not exist
if (!mediaInternalDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Consts.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == Consts.MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
// ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
if (requestCode == Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
comImage.compressImage(fileUri.toString());
Picasso.with(this).load(fileUri).fit().centerCrop().into(ivPhoto);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture0
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
storage permission already checked on manifest
i used a combination of answers to make it work so i ended up with this code:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Date dat = Calendar.getInstance().getTime();
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-mm-dd-hh:mm:ss");
String nameFoto = simpleDate.format(dat) + ".png";
String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ File.separator +nameFoto;
File ff = new File(filename);
try {
ff.createNewFile();
//imageUri = Uri.fromFile(ff);
imageUri = FileProvider.getUriForFile(IngresarFactura.this, BuildConfig.APPLICATION_ID + ".provider",ff);
//imageUri = new Uri(filename).
if (imageUri.getPath() == null){
mensaje.setText(filename+ " Error path es nulo.");
}
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
//COMPATIBILITY
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP) {
cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} else {
List<ResolveInfo> resInfoList = IngresarFactura.this.getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
IngresarFactura.this.grantUriPermission(packageName, imageUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
//COMPATIBILITY
activityResultLaunch.launch(cameraIntent);
}
you also have to do this as answered here:
https://stackoverflow.com/a/45751453/16645882

Saving image taken from camera into INTERNAL storage

I just got started in Android Programming and I am creating an android application in which the user is allowed to key in information, take a picture with ImageView implemented and SAVE the information. I've gotten up to the point where I am able to display the image taken into ImageView. However, I am unable to save the image taken into my phone's internal storage. Which means, whenever I try to save the information, including the ImageView (image from camera), only the image disappears. I've followed this guide on http://www.androidhive.info/2013/09/android-working-with-camera-api/ but it does not work as my phone has no SD card storage.
I've read a bunch of questions on here but they do not fix the problem.
So if anyone could give me a detailed procedure on how to edit this code in such a way that I can save/read the image into/from my INTERNAL storage that would be great! Thank you.
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
}
This is my current code:
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
private ImageView ItemPic;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_entry);
date = (EditText) findViewById(R.id.date);
amount = (EditText) findViewById(R.id.amount);
item = (EditText) findViewById(R.id.item);
add = (Button) findViewById(R.id.add_b);
add.setOnClickListener(onAdd);
camera = (ImageButton) findViewById(R.id.camera);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
// Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
ItemPic = (ImageView) findViewById(R.id.itempic);
entryId = getIntent().getStringExtra("ID");
if (entryId != null) {
load();
}
}
/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
ItemPic.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
ItemPic.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
getOutputMediaFile() is returning a directory, not a file. You need to specify a path to a (not-yet-existing) file where you want the image to be written.
This is illustrated in this activity from this sample application:
package com.commonsware.android.camcon;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
public class CameraContentDemoActivity extends Activity {
private static final int CONTENT_REQUEST=1337;
private File output=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.jpeg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CONTENT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CONTENT_REQUEST) {
if (resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/jpeg");
startActivity(i);
finish();
}
}
}
}

Camera Intent doesn't return to previous activity in some versions of android

I have implemented many imageviews with a camera icon so that when the user touches on the icon it starts the camera and when the picture is taken it returns to the original activity where the camera intent was called and display the captured image in the imageviews.
The problem is this works ok with in my Jellybean 4.2.2. But in some phones having kitkat and Jellybean 4.2.1, when the camera is loaded and the picture is taken it gives an option to save or discard the captured image (in my phone no option is given to save) and when i click save the app crashes. Sometimes even in my phone it returns to previous activity but doesn't show the captured images.
Please help me if you can.I am posting the essential code below
ImageView photo1,photo2,photo3,photo4,photo5;
int photonum=0;
String image1,image2,image3,image4,image5;
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "MagicPlaces";
private Uri fileUri; // file url to store image/video
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_uploadtab1);
photo1= (ImageView) findViewById(R.id.photo1);
photo2= (ImageView) findViewById(R.id.photo2);
photo3= (ImageView) findViewById(R.id.photo3);
photo4= (ImageView) findViewById(R.id.photo4);
photo5= (ImageView) findViewById(R.id.photo5);
photo1.setOnClickListener(this);
photo2.setOnClickListener(this);
photo3.setOnClickListener(this);
photo4.setOnClickListener(this);
photo5.setOnClickListener(this);
}
public void onClick(View v) {
int id=v.getId();
if(id==R.id.photo1){
captureImage();
photonum=1;
}if(id==R.id.photo2){
captureImage();
photonum=2;
}
if(id==R.id.photo3){
captureImage();
photonum=3;
}
if(id==R.id.photo4){
captureImage();
photonum=4;
} if(id==R.id.photo5){
captureImage();
photonum=5;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case(100):{
if (resultCode == RESULT_OK) {
String fileuri=data.getData().getPath();
previewCapturedImage(fileuri);
}
else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image",Toast.LENGTH_SHORT)
.show();
}
}
break;
}
}
private void previewCapturedImage(String fileUr) {
try {
// System.out.println(fileUr);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 16;
Bitmap bitmap = BitmapFactory.decodeFile(fileUr,
options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", encodedImage);
if(photonum==1){
photo1.setImageBitmap(bitmap);
image1=encodedImage;
}
if(photonum==2){
photo2.setImageBitmap(bitmap);
image2=encodedImage;
}
if(photonum==3){
photo3.setImageBitmap(bitmap);
image3=encodedImage;
}
if(photonum==4){
photo4.setImageBitmap(bitmap);
image4=encodedImage;
}
if(photonum==5){
photo5.setImageBitmap(bitmap);
image5=encodedImage;
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
//System.out.println(fileUri);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}

Capturing and storing multiple images in android [duplicate]

I seem to be having trouble creating a Bitmap from fileUri.
I would like to be able to set this Bitmap to an Imageview for previewing the image, and later adding elements to the image.
Any ideas why the image does not get set properly?
public class FeedActivity extends Fragment implements OnClickListener {
ImageView m_ImageView;
ImageButton btnCamera, btnGallery;
private final String TAG_CAMERA_FRAGMENT = "camera_fragment";
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;
public static final int MEDIA_TYPE_IMAGE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_feed, container, false);
m_ImageView = (ImageView) view
.findViewById(R.id.imageViewFeed);
btnCamera = (ImageButton) view.findViewById(R.id.btn_Camera);
btnCamera.setOnClickListener(this);
btnGallery = (ImageButton) view.findViewById(R.id.btn_Gallery);
btnGallery.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_Camera:
Log.e("CAMERA", "CAMERA BUTTON PRESSED");
takePicture();
break;
case R.id.btn_Gallery:
Log.e("Gallery", "GALLERY BUTTON PRESSED");
break;
}
}
public void takePicture() {
// create Intent to take a picture and return control to the calling
// application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == getActivity().RESULT_OK) {
Log.e("ONACTIVITYRESULT",
"-----------------RESULT_OK----------------");
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath());
m_ImageView.setImageBitmap(bitmap);
// Bundle bundle = new Bundle();
// bundle.putParcelable("URI", fileUri);
//
// Fragment fragment = new PictureEditActivity();
// fragment.setArguments(bundle);
//
// getFragmentManager()
// .beginTransaction()
// .replace(R.id.contentFragment, fragment,
// TAG_CAMERA_FRAGMENT).commit();
if (fileUri != null) {
Log.e("CAMERA", "Image saved to:\n" + fileUri);
Log.e("CAMERA", "Image path:\n" + fileUri.getPath());
}
} else if (resultCode == getActivity().RESULT_CANCELED) {
Log.e("ONACTIVITYRESULT",
"-----------------RESULT_CANCELLED----------------");
} else {
}
}
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Pixagram");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Pixagram", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
}
It appears as if I have found a solution.
http://www.androidhive.info/2013/09/android-working-with-camera-api/
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
m_ImageView.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}

why the file object become null after camera capture

my code
public class MainActivity extends Activity {
private View TakePhotoBtn;
private ImageView ProductPhoto;
private Button ReviewBtn;
public static File file;
private static final int CAMERA_REQUEST = 1888;
#Override
protected void onCreate(Bundle savedInstanceState) {
.....
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
void TakePhoto() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.png");
Uri imageUri = Uri.fromFile(file);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
imageUri);
BugTrackerApp.app.file =file ;
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
// this line is getting null value .... why
file = BugTrackerApp.app.file ;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ProductPhoto.setImageBitmap(bitmap);
ReviewAct.ImageFile = file;
}
}
}
Presumably your process was terminated while you were in the background. Do not rely upon static data members for anything more than a cache.
what did you do to BugTrackerApp? Have you checked it?
Why do you need the two lines?
BugTrackerApp.app.file =file ;
file = BugTrackerApp.app.file ;
You created a file to store captured image, and decoded it in onActivityResult. so this line
file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.png");
is enough.

Categories

Resources