Orientation changes cause app to FC

198 Views Asked by At

I'm working on an app that scans barcodes, when it gets a successful scan it will show a Dialog with the code that was scanned and depending on what was contained within the bar/QR code it will show a button to open a browser, send an SMS, etc. While the Dialog is showing, if the screen changes orientation it crashes. I have got it working to where the orientation can change a couple times before it crashes, but when I check LogCat it says that a NullPointerException is causing the FC. Before I had implemented @CommonsWare's suggestions I could get it to rotate an arbitrary amount of times before crashing, but since I've implemented them it FC's on the second orientation change always. When I launch this in debug mode I can rotate the phone as many times as I want and as quickly as I want but as soon as I launch it in normal mode it always crashes.

Class Field:

private String currentType;

I implemented onSaveInstanceState():

@Override
public void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);    
    outState.putString("savedType", currentType);
}

Also onRestoreInstanceState():

@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
    super.onRestoreInstanceState(savedInstanceState);
    currentType = savedInstanceState.getString("savedType");
}

Update


I've updated the above code to what it currently is, following @CommonsWare's suggestions. I've also edited my post for integrity.

I'm also using CM7 (Android Version - 2.3.7, Kernel Version - 2.6.37.6-cyanogenmod-g0799e00 android@portatile #1, Mod Version - CyanogenMod-7-11152011-NIGHTLY-N1, Build Number - GWK74).

1

There are 1 best solutions below

5
On

In onPause() I have used this.onRetainNonConfigurationInstance() to try to remedy that but it doesn't appear to have made a difference.

You do not call onRetainNonConfigurationInstance(). Android calls onRetainNonConfigurationInstance().

I guess it also seems to me that this should work, according to all the posts I've read about handling orientation changes.

You need to use better sources.

To attempt to repair your code:

Step #1: Delete the android:configChanges attribute from your <activity> in the manifest

Step #2: Delete your onConfigurationChanged() method

Step #3: Either move your onResume() logic into onCreate() to populate currentType, or do not attempt to use currentType before onResume()

Even better would be to replace your whole onRetainNonConfigurationInstance()/getLastNonConfigurationInstance() with onSaveInstanceState()/onRestoreInstanceState(), putting your String in the Bundle.

Here is a sample project demonstrating the use of onSaveInstanceState(). Here is a sample project demonstrating the use of onRetainNonConfigurationInstance().