I try to create an app that can capture image from camera and show the result based on image path. Inside the button which handles capturing image as below
btnImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory() + File.separator + "Nama_foto_" + waktu + ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
intent.putExtra("return-data", true);
getParentFragment().startActivityForResult(intent, CAPTURE_IMAGE);
}catch (ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast toast = Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
});
And as a respon from camera capturing Im writing below code
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == CAPTURE_IMAGE) {
performCrop();
}
else if(requestCode == PIC_CROP){
//get the returned data
Bundle extras = data.getExtras();
//get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
picturePath = file.getAbsolutePath();
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thePic.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
out.write(bytes.toByteArray());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
//retrieve a reference to the ImageView
//ImageView picView = (ImageView)findViewById(R.id.picture);
//display the returned cropped image
imgView.setImageBitmap(thePic);
}
try {
}catch (Exception e) {
Toast.makeText(getActivity(), "Maaf gagal mengambil foto.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
Variable picturePath declared outside OnCreateView as an empty string. The problem is, whenever I run the app and capture the image. The image didnt show immediately in the gallery but instead I need to rerun the app (thru android studio) to see the image in gallery. It seems like something inside oncreateview trigger the event. But I still cant figure out what.
Pls help me fix the issue. Thanks
it seems that your question should be rephrased differently: this may solve your problem
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
reference : How can I update the Android Gallery after a photo?