我正在显示SD卡中的图片。我在谷歌搜索了很多,并得到以下代码
我有一个按钮,点击即可调用相机功能。
public void onClick(View arg0) {
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
photoPath = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));
System.out.println(photoPath);
startActivityForResult(intent, TAKE_PICTURE);
}
我在onActivityResult函数中使用了以下代码。
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {
System.out.println("after activity"+photoPath);
Uri selectedImage = photoPath;
getContentResolver().notifyChange(selectedImage, null);
ivThumbnailPhoto = (ImageView) findViewById(R.id.ivThumbnailPhoto);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
ivThumbnailPhoto.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
问题是我将photoPath值变为null并且最终会出现nullpointer异常。请帮我找出问题。
提前致谢
答案 0 :(得分:2)
您将文件路径的值作为intent extra传递,这是正确的行为。
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));//here save this uri you are passing as extra.
在onActivityResult
中,如果RESULT_CODE
OK
使用您URI
以上传递的EXTRA_OUTPUT
,则您将从相机获取null意图/数据,所以不要使用它。
编辑: - 当您退出活动并返回时,您的PhotoPath变量可能会变为NULL,这里有两个解决方案。
1)使photopath / uri静止。
2)使用以下代码在外出时保存,并在进入活动时获取值。
/**
* 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", photopath);
}
/*
* Here we restore the fileUri again
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the path
photoPath = savedInstanceState.getParcelable("file_uri");
}