How to retrieve the images from the particular folder? - android

I am trying to take picture and save it in a particular folder and retrieve it in a list view. I have done the first part that is show to store it in a particular folder, but I don't know how to retrieve it.
Here the taken images is stored in a hello camera folder which is inside pictures. The below code can also record the video. Please give me the code to retrieve the images only from the particular folder. I need this code because to store the documents with security.
My code for storing images
public class photo extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
Button submit;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
context = this;
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
submit = (Button) findViewById(R.id.button2);
name = (EditText) findViewById(R.id.imagename);
//n1= (EditText) findViewById(R.id.imagename);
// final String Uname = name.getText().toString();
/**
* Capture image button click event
*/
Calendar cal;
cal = Calendar.getInstance();
String currDate = cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.YEAR);
mydb = this.openOrCreateDatabase(DataProvider.DATABASE_NAME, Context.MODE_PRIVATE, null);
Cursor cs = mydb.rawQuery("select * from '" + DataProvider.TBL_PRE + "'", null);
// cs = getContentResolver().query(DataProvider.PRE_URI, null,DataProvider.DATE+"="+currDate, null, null);
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String err = val();
if (err.length() <= 0) {
String uname = name.getText().toString();
System.out.println("++uname--->" + uname);
ContentValues values = new ContentValues();
values.put(DataProvider.NAME1, uname);
getContentResolver().insert(DataProvider.PRE_URI, values);
System.out.println("\n values" + values.toString());
startActivity(new Intent(photo.this, preview.class));
overridePendingTransition(R.anim.pull_in_left, R.anim.push_out_right);
}
else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setMessage(err);
alertDialog.show();
}
}
});
/*submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String err = val();
if (err.length() <= 0) {
String uname = name.getText().toString();
System.out.println("uname--->" + uname);
ContentValues values = new ContentValues();
values.put(DataProvider.NAME1, uname);
System.out.println("^^^"+uname);
//values.put(DataProvider.DATE, date.getText().toString());
getContentResolver().insert(DataProvider.PRE_URI, values);
System.out.println("\n values" + values.toString());
Intent i = new Intent(photo.this, preview.class);
startActivity(i);}
}
});
*/
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* 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");
}
/**
* Recording video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* 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();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.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);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception 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 if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(photo.this,preview.class));
overridePendingTransition(R.anim.pull_in_left,R.anim.push_out_right);
finish();
System.exit(0);
}
public String val() {
String err = "";
if (name.getText().toString().length() <= 0) {
err += "Enter the Name \n";
}
return err;
}
}
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* 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();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.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);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception 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 if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(photo.this,preview.class));
overridePendingTransition(R.anim.pull_in_left,R.anim.push_out_right);
finish();
System.exit(0);
}
public String val() {
String err = "";
if (name.getText().toString().length() <= 0) {
err += "Enter the Name \n";
}
return err;
}
}

try this
private void getImages() {
String[] filenames = new String[0];
File path = new File(Environment.getExternalStorageDirectory() + "/Favorite");// add here your fo;der name
if (path.exists()) {
filenames = path.list();
}
for (int i = 0; i < filenames.length; i++) {
imagesPathArrayList.add(path.getPath() + "/" + filenames[i]);
Log.e("FAV_Images", imagesPathArrayList.get(i));
//Bitmap mBitmap = Bitmap.decodeFile(path.getPath()+"/"+ fileNames[i]);
///Now set this bitmap on imageview
}
}
don't forget to add permission in manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

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

How to display capture image from camera and display in imageview from file path? [duplicate]

This question already has answers here:
Capture Image from Camera and Display in Activity
(19 answers)
Closed 6 years ago.
My problem after taking a photo and then createImageFile .. onActivityResult, photo does not appear on img_photo. how to make appear in img_photo ?
img_photo = (ImageView) findViewById(R.id.imgPhoto);
// take a photo from camera
imgBtnCamera = (ImageButton) findViewById(R.id.imgBtnCamera);
imgBtnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(PhotoSubmitActivity.this,
"com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
});
Create image file
// Create image file
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
Log.v("This is totally working", "Yeah!");
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
img_photo.setScaleType(ImageView.ScaleType.CENTER_CROP);
img_photo.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I attended training on this link Taking Photos Simply
i had same problem too.but i solved it.
#Driyanto Saputro see in my code where i placed a comment for save Captured image in ImageView.
also Note : i am working on Custom Camera not Using Existing Camera.
i paste my code below to Save Captured image in imageView.
public void CaptureImage() {
mCamera.takePicture(null, null, new Camera.PictureCallback() {
private File imageFile;
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
// Convert byte array into bitmap
final Bitmap originalBitmap = MainActivity.decodeSampledBitmapFromByte(getApplicationContext(), data);
// Rotate Image
Matrix rotateMatrix = new Matrix();
final Bitmap rotatedBitmap;
if (mCameraId == CAMERA_FACING_FRONT) {
rotateMatrix.postRotate(270);
} else {
rotateMatrix.postRotate(90);
}
rotatedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight(), rotateMatrix, false);
final File imageFolder;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
imageFolder = new File(Environment.getExternalStorageDirectory() + "/CameraApp/Images");
} else {
imageFolder = new File(Environment.getExternalStorageDirectory() + "/CameraApp/Images");
}
boolean success = true;
if (!imageFolder.exists()) {
success = imageFolder.mkdirs();
}
if (success) {
java.util.Date date = new java.util.Date();
imageFile = new File(imageFolder.getAbsolutePath() + File.separator + getFileNameCustomFormat() + " " + "Image.jpg");
SavedImagePath = getFileNameCustomFormat() + " " + "Image.jpg";
// imageFile.createNewFile();
} else {
Toast.makeText(getBaseContext(), "Image Not saved", Toast.LENGTH_SHORT).show();
return;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Save image into gallery
if (rotatedBitmap != null) {
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
}
FileOutputStream file_out = new FileOutputStream(imageFile);
file_out.write(outputStream.toByteArray());
file_out.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, imageFile.getAbsolutePath());
getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(getApplicationContext(), "Photo Captured", Toast.LENGTH_SHORT).show();
// Code For Captured Image Save in a ImageView.
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
String imagePath = imageFolder.getAbsolutePath() + File.separator + SavedImagePath;
Uri myURI = Uri.parse(imagePath);
imgBtnThumbnail.setImageURI(myURI);
Toast.makeText(getApplicationContext(), "Photo Saved on ImageView", Toast.LENGTH_SHORT).show();
}
});
mCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
I hope it will help You.(:
Try this way it will help
public class MainActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* 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");
}
/**
* Recording video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* 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();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.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);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception 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 if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
http://www.androidhive.info/2013/09/android-working-with-camera-api/

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

how to use a timer in android which causes a program to run for 2 minutes when a button is pressed and then stop automatically after two minutes

I am making an app in which i have a button which clicks pictures.Till here I have done.Now I want that the user can take pictures for only two minutes after clicking the button.And also he has to take 5 pictures.So if the timer expires and 5 pics are not taken then restart the camera or else save the picture.I don't understand how to automatically stop a timer after two minutes.
Please guide.I am new to android.
package com.mycamera2;
public class MainActivity extends ActionBarActivity
{
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Car Camera";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private Button btnCapturePicture;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnCapturePicture.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// capture picture
captureImage();
}
});
// Checking camera availability
if (!isDeviceSupportCamera())
{
Toast.makeText(getApplicationContext(),"Sorry! Your device doesn't support camera",Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
private boolean isDeviceSupportCamera()
{
if (getApplicationContext().getPackageManager().hasSystemFeature( PackageManager.FEATURE_CAMERA))
{
// this device has a camera
return true;
} else
{
// no camera on this device
return false;
}
}
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);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
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
{
imgPreview.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);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e)
{
e.printStackTrace();
}
}
/**
* 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
String root = Environment.getExternalStorageDirectory().toString();
//File myDir = new File(root + "/vanjasaved_images");
// File mediaStorageDir = new File(root + "/.sidvanjasaved_images");
File mediaStorageDir = new File(root + "/.external_sd");
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 if (type == MEDIA_TYPE_VIDEO)
{
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
} else
{
return null;
}
return mediaFile;
}
}
You can use android Timer Timer doc
Start timer when button is clicked
TimerTask timerTask = new TimerTask () {
#Override
public void run () {
// your code here... check if 5 image taken and cancel the timer
}
};
new Timer().schedule(timerTask, 2*60*1000);
I didn't test it, you can try it... every Url that you get in your activityResult , you put it in the ArrayList.
/**
* flag to check if you have already lunched the handler
*/
private static boolean isHandlerLunched = false;
/**
* Delay max to take 5 pictures
*
* #value in milliseconds
*/
private static final int DELAY_MAX = 60*1000*2;
/**
* ArrayList<String> containing the URLS of the pictures
*/
private static ArrayList<String> pictureUrls = new ArrayList<String>();
/**
* open the camera activity for result
*/
private void captureImage()
{
// if it is the first click to take the first picture
if (!isHandlerLunched){
// initialize the list again
pictureUrls = new ArrayList<String>();
// lunch the handler to delay
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void run() {
//TODO the delay is finished , you do your staff of checking
// I propose you to add the URLs of each picture in an ArrayList<String>,
// and here you check the size of this list
if (pictureUrls.size()<5) {
// do staff
} else {
// do staff
}
}
}, DELAY_MAX );
}
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);
}

Image capturing in android is working only on emulator not in phone

I have followed this
to take an image using android inbuilt camera and save the image in sd card. The code is working fine with the emulator. But when i installed the apk in phone(samsung galaxy s3). the application will not take images.
My code is follows. Please have a look.
public class MainActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
protected Context context = this;
public static int count = 0;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
protected static final String TAG = "MyCameraAppss";
private Camera autoCam ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
captureImage();
}
});
}
private void captureImage(){
//Detecting camera hardware
boolean isCameraAvailable = checkCameraHardware(context);
if(isCameraAvailable){
Toast.makeText(context, "Camera found", Toast.LENGTH_SHORT).show();
//Accessing cameras
autoCam = getCameraInstance();
if(autoCam!=null){
autoCam.open();
Toast.makeText(context, "Camera is accesses successfully", Toast.LENGTH_SHORT).show();
autoCam.takePicture(null, null, mPicture);
Toast.makeText(context, "picture is taken and going to sleep for a sec", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Toast.makeText(context, "Camera instance not available", Toast.LENGTH_SHORT).show();
}
Toast.makeText(context, "After slept going to release the camera", Toast.LENGTH_SHORT).show();
autoCam.release();
Toast.makeText(context, "Camera released successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "cannot access the camera", Toast.LENGTH_SHORT).show();
}
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Toast.makeText(context, "Error creating media file, check storage permissions:", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Error creating media file, check storage permissions: ");
return;
}else{
Toast.makeText(context, "Save: Pic file is found going to write", Toast.LENGTH_SHORT).show();
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(context, "Save: Pic is saved successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(context, "File not found: " + e.getMessage(), Toast.LENGTH_LONG).show();
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Toast.makeText(context, "Error accessing file: " + e.getMessage(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Error accessing file: " + e.getMessage());
}catch (Exception e) {
Toast.makeText(context, "Other Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
};
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
e.printStackTrace();
}
return c; // returns null if camera is unavailable
}
/** 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), "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("MyCameraApp", "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+"Amith" + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
The image is saved in the location
I have installed the apk on my phone and clicks the camera button mentioned in the first image, only "camera released toast" is displayed.
Is it necessary to load preview in our page?
i am very new with camera API.
Please guide me to resolve this
Thank you
This is my own blog here you will get description of your problem.
http://uniqueandroidtutorials.blogspot.in/2013/02/code-to-start-camera-with-build-in.html
Hope it will helps you..Thanks
Did you add this permission to AndroidManifest.xml file
<uses-feature android:name="android.hardware.camera" />
Then refer this codes. It work for me.
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri;
private static int RESULT_LOAD_IMAGE = 1;
public void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
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");
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
if(latlon==null)
latlon="";
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "CERS");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath()+ File.separator+ timeStamp + "_--"+ latlon +"--.jpg");
}
return mediaFile;
}
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
IMGS.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, 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.ShowAlert("User cancelled image capture", 0,false);
} else {
// failed to capture image
toast.ShowAlert("Sorry! Failed to capture image",0,false);
}
}
/***/
/** Browse Images **/
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);
IMGS.setImageBitmap(bitmap);
}
}

Categories

Resources