I'm trying to get my app to start a camera intent in order to take a picture and save it into a directory as well as show a thumbnail in the main view, but I don't quite seem to get it right. Here's the methods I'm using:
@RequiresApi(api = Build.VERSION_CODES.M)
private void dispatchTakePictureIntent() {
if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
5);
}
}
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if(photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getContext(),
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
And here's the OnActivityResult
:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
image.setImageBitmap(imageBitmap);
}
}
I seem to be getting a NullPointerException
in two different places, at:
photoFile.createNewFile();
image.setImageBitmap(imageBitmap);
How can I fix this?
Change your onActivityResult
to
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
onCaptureImageResult(data);
}
}
for setting in a thumbnail pass the data
in your ImageView
variable like this:
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
byteArray = bytes.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageBitmap(thumbnail);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments