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).
You do not call
onRetainNonConfigurationInstance()
. Android callsonRetainNonConfigurationInstance()
.You need to use better sources.
To attempt to repair your code:
Step #1: Delete the
android:configChanges
attribute from your<activity>
in the manifestStep #2: Delete your
onConfigurationChanged()
methodStep #3: Either move your
onResume()
logic intoonCreate()
to populatecurrentType
, or do not attempt to usecurrentType
beforeonResume()
Even better would be to replace your whole
onRetainNonConfigurationInstance()
/getLastNonConfigurationInstance()
withonSaveInstanceState()
/onRestoreInstanceState()
, putting yourString
in theBundle
.Here is a sample project demonstrating the use of
onSaveInstanceState()
. Here is a sample project demonstrating the use ofonRetainNonConfigurationInstance()
.