我正在尝试从系统的默认相机应用程序捕获图像。但是在我的onActivityResult()方法运行时单击该图像后,它显示意图对象为null。谁能告诉我我的方法有什么错误。
我已经使用了android文档中的代码来捕获图像并将其存储在设备的外部存储中
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_and_pricefrag);
rotateButton=findViewById(R.id.rotate_btn);
cancelButton=findViewById(R.id.cancel_btn);
checkButton=findViewById(R.id.check_btn);
mPhoto = findViewById(R.id.add_photo);
imageView = findViewById(R.id.imageCapture);
mPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPictureDialog();
}
});
private void setImageinScroll(Bitmap bitmap,int count){
mGallery = findViewById(R.id.linearScroll);
View view = mInflater.inflate(R.layout.horizontal_scroll, mGallery, false);
ImageView imageViewscroll = view.findViewById(R.id.image1);
imageViewscroll.setImageBitmap(bitmap);
mGallery.addView(view, count);
}
private void captureImage() {
if (ContextCompat.checkSelfPermission(CameraAndPrizeFrag.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission not granted", Toast.LENGTH_SHORT).show();
if (ActivityCompat.shouldShowRequestPermissionRationale(CameraAndPrizeFrag.this, Manifest.permission.CAMERA)) {
Toast.makeText(this, "No Explaination needed", Toast.LENGTH_SHORT).show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
} else {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
capture();
}
}
private void capture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
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(this,
"com.example.rajat.android_test",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA);
}
}
}
String currentPhotoPath;
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
currentPhotoPath = image.getAbsolutePath();
return image;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
} else {
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
// bitmap = compressImage(bitmap);
// String path = saveImage(bitmap);
//Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
if (requestCode ==CAMERA&& resultCode == RESULT_OK) {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Uri uri = (Uri)bundle.get(MediaStore.EXTRA_OUTPUT);
Log.e("DataNull", "onActivityResult: " +data.getData().toString() );
//Bitmap imageBitmap = (Bitmap) data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
else if (requestCode == SET_IMAGE) {
byte[] arrFinal = data.getByteArrayExtra("returnImage");
FinalBitmap = BitmapFactory.decodeByteArray(arrFinal, 0, arrFinal.length);
imageView.setImageBitmap(FinalBitmap);
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Log.e("camera12345", "onActivityResult: 3" );
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {"Select photo from gallery", "Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
captureImage();
// dispatchTakePictureIntent();
// takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
}
日志:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
at com.example.rajat.android_test.CameraAndPrizeFrag.onActivityResult(CameraAndPrizeFrag.java:315)
at android.app.Activity.dispatchActivityResult(Activity.java:7590)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4416)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4465)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
2019-06-17 23:08:03.627 831-1003/? E/ThermalEngine: read_thermal_config
2019-06-17 23:08:03.628 831-1003/? E/ThermalEngine: set_cpufreq_govoner
2019-06-17 23:08:03.689 1517-1707/? E/InputDispatcher: channel '3e3f9e8 com.example.rajat.android_test/com.example.rajat.android_test.CameraAndPrizeFrag (server)' ~ Channel is unrecoverably broken and will be disposed!
2019-06-17 23:08:03.689 1517-1707/? E/InputDispatcher: channel '1d3a521 com.example.rajat.android_test/com.example.rajat.android_test.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!