相机活动返回 null android [英] Camera activity returning null android
问题描述
我正在构建一个应用程序,我想在其中通过默认相机活动捕获图像并返回到我的活动并将该图像加载到 ImageView 中.问题是相机活动总是返回空值.在我的 onActivityResult(int requestCode, int resultCode, Intent data)
方法中,我获取的数据为 null
.这是我的代码:
I am building an application where I want to capture an image by the default camera activity and return back to my activity and load that image in a ImageView. The problem is camera activity always returning null. In my onActivityResult(int requestCode, int resultCode, Intent data)
method I am getting data as null
. Here is my code:
public class CameraCapture extends Activity {
protected boolean _taken = true;
File sdImageMainDirectory;
Uri outputFileUri;
protected static final String PHOTO_TAKEN = "photo_taken";
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameracapturedimage);
File root = new File(Environment
.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator);
root.mkdirs();
sdImageMainDirectory = new File(root, "myPicName");
startCameraActivity();
} catch (Exception e) {
finish();
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
}
protected void startCameraActivity() {
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
{
if(resultCode==Activity.RESULT_OK)
{
try{
ImageView imageView=(ImageView)findViewById(R.id.cameraImage);
imageView.setImageBitmap((Bitmap) data.getExtras().get("data"));
}
catch (Exception e) {
// TODO: handle exception
}
}
break;
}
default:
break;
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(CameraCapture.PHOTO_TAKEN)) {
_taken = true;
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(CameraCapture.PHOTO_TAKEN, _taken);
}
}
我做错了什么吗?
推荐答案
你之所以出错,是因为你做错了.
You are getting wrong because you are doing it wrong way.
如果您将额外的参数 MediaStore.EXTRA_OUTPUT
与相机意图一起传递,则相机活动会将捕获的图像写入该路径,并且不会在 onActivityResult
方法.
If you pass the extra parameter MediaStore.EXTRA_OUTPUT
with the camera intent then camera activity will write the captured image to that path and it will not return the bitmap in the onActivityResult
method.
如果你检查你正在传递的路径,那么你就会知道实际上相机已经在该路径中写入了捕获的文件.
If you will check the path which you are passing then you will know that actually camera had write the captured file in that path.
For further information you can follow this, this and this
这篇关于相机活动返回 null android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!