Reputation:
I am trying to build a Camera app.
This is the code of 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();
}
}
}
}
After I Capture an image I get this message:
"Unfortunately,Camera tutorial has stopped";
Log cat says
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
What is the problem?
Upvotes: 2
Views: 1115
Reputation: 133560
You do not have
setContentView(R.layout.mylayout);
So
ImageView iv = (ImageView) findViewById(R.id.image_frame);// fails
findViewById
looks for a view with the id mentioned in the current inflateed layout. So you need to set the content of the layout to the activity first and then initialize views.
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);
}
Make sure you have the required permission in manifest file
http://developer.android.com/reference/android/hardware/Camera.html
http://developer.android.com/guide/topics/media/camera.html
Upvotes: 1