问题
I am trying to use the built-in camera application to take a photo and view it through an ImageView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
addButtonListeners();
startCamera();
}
private void startCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, PHOTO_TAKEN);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == PHOTO_TAKEN) {
Bundle extras = intent.getExtras();
photo = (Bitmap) extras.get("data");
if (photo != null) {
ImageView image = (ImageView) findViewById(R.id.image_background);
image.setImageBitmap(photo);
} else {
Toast.makeText(this, R.string.unable_to_read_photo, Toast.LENGTH_LONG)
.show();
}
}
}
When holding the phone in portrait position this code works just fine, however when I take the picture in landscape it breaks, any ideas why or how to solve this?
回答1:
Question in not defined with enough details to answer it for sure, but my guess would be the same as Shani Goriwal .
It looks like problems with configuration changes event - which happens each time orientation is changed (from landscape to portrait).
Try to add to AndroidManifest of your app following lines: android:configChanges="orientation|screenSize"
(more details: http://developer.android.com/guide/topics/resources/runtime-changes.html)
回答2:
I found a tutorial that explains how to appropriately use the in built camera. Here is the link.
I am relativly new on android but from what I have read is the every time the display rotates android creates a new instance of some sort. So you have to save the instance of the rotation and this is done with the following code:
/**
* 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", fileUri);
}
/*
* Here we restore the fileUri again
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
If you click on the link you should go to bullet number 11. Avoiding NullPointerException after taking camera picture. The real hero here is Ravi Tamada who does an excellent tutorial on using the camera. I recommend reading the whole tutorial.
Again I am new at this so if there is any corrections on what I have wrote here please correct.
来源:https://stackoverflow.com/questions/17920030/android-error-occurs-when-taking-a-picture-in-landscape