Camera activity at which uri goes to zero when screen orientation changes

I set the data member, imageUri and passed this to the intent, which triggers the camera activity. In the action of the camera, I take a picture and rotate the screen before clicking the checkbox to return to my activity. When I do this, imageUri is null when onActivityResult is called. If I do not rotate the screen, everything works fine, and imageUri is not null.

onConfigurationChanged does not receive a call in my activity, so this is not a problem.

public void takePhoto() { //define the file-name to save photo taken by Camera activity fileName = getFileNameDate(); //create parameters for Intent with filename ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, fileName); values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera"); imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); //create new Intent Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(intent, picture_result_code); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i("Camera_onActivityResult", "Got activity result requestCode = " + requestCode + " resultCode: " + resultCode); super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case picture_result_code: if (resultCode == Activity.RESULT_OK) { try { Log.i("Camera", "Preparing to upload image..."); picFile = convertImageUriToFile(imageUri); // Here imageUri is null and causing crash uploadFile(picFile.getPath()); } catch (Exception e) { Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show(); Log.e("Camera", e.toString()); e.printStackTrace(); } } } } 

Is there any other way that I should get an image?

thanks

+4
source share
2 answers

I believe imageUri is a field in your work, right? if you rotate the device, the action is destroyed and restarts, and your field is null. You must save the URI as part of the state of your activity. There are several possible ways to achieve this, namely: use onSaveInstanceState (), see here for more details: http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState%28android.os.Bundle % 29

+2
source

The screen orientation lock of the calling operation fixed the problem for me. If you do not want to block your own, you can create an Activity with a locked orientation only to call the camera, and then return the result to your "real" activity.

To block screen orientation, put this in the activity definition in the manifest (both lines):

 android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation|screenSize" 

a "portrait" can also be a "landscape"

0
source

Source: https://habr.com/ru/post/1395626/


All Articles