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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…