Skip to content Skip to sidebar Skip to footer

Android GetContentResolver().insert() Occasionally Returning Null

I have a piece of code that aims to launch the android camera, let the user take a photo and eventually keep the uri of the image once it is saved. So far I have managed to get it

Solution 1:

You really have to take to heart the first rule of Android Activities: Android may decide at any time to kill your activity, resetting all member variables in the process. It will simply rebuild the activity once it needs to handle onActivityResult... but as you initialized mImageCaptureUri in your specific handler, it will now be null.

The classic cause in your example would be an orientation change during the launched "capture an image" activity (orientation changes will typically kill the activity), but there is a myriad of other reasons why android would decide to terminate it (lack of memory, incoming calls, phone having a bad hair day, etc).

The solution is to store and restore state like mImageCaptureUri in onSaveInstanceState(), and restore it in the onCreate() of the Activity, i.e.

   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if (savedInstanceState != null)
        {
            mImageCaptureUri = savedInstanceState.getParcelable("imageCaptureUri");
        }
    }

    protected void onSaveInstanceState(Bundle outState)
    {
        outState.putParcelable("imageCaptureUri", mImageCaptureUri);
    }

Post a Comment for "Android GetContentResolver().insert() Occasionally Returning Null"