我正在尝试构建一个相机应用。
这是MainActivity的代码:
public class MainActivity extends Activity {
public static int CAMERA_REQUEST_KEY = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_KEY);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_KEY) {
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
Bitmap bmp = (Bitmap) bundle.get("data");
ImageView iv = (ImageView) findViewById(R.id.image_frame);
iv.setImageBitmap(bmp);
} else {
Toast.makeText(getApplicationContext(), "Operation Failed", Toast.LENGTH_LONG).show();
}
}
}
}
拍摄图像后,我收到此消息:
“不幸的是,相机教程停止了”;
Log cat说
11-13 21:23:00.107: E/AndroidRuntime(17967): java.lang.RuntimeException: Unable to resume activity {com.example.cameratutorial/com.example.cameratutorial.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { act=inline-data dat=content://media/external/images/media/20787 typ=image/jpeg (has extras) }} to activity {com.example.cameratutorial/com.example.cameratutorial.MainActivity}: java.lang.NullPointerException
有什么问题?
答案 0 :(得分:1)
你没有
setContentView(R.layout.mylayout);
所以
ImageView iv = (ImageView) findViewById(R.id.image_frame);// fails
findViewById
查找当前inflateed布局中提到的id的视图。因此,您需要先将布局内容设置为活动,然后初始化视图。
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
iv = (ImageView) findViewById(R.id.image_frame);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_KEY);
}
确保您在清单文件中具有所需的权限
http://developer.android.com/reference/android/hardware/Camera.html