I program my first Android app and am very new to Android development (as well as Java). I have PreferenceActivity and noticed that when activity is shown and I turn off mobile its onCreate() is called once again. Even more confusing is that static member MyFirstAppActivity.camera is not existing anymore causing exceptions. I can put check for null in there but I wonder why is this happening and whats the best way to avoid it?
public class SettingsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Root
addPreferencesFromResource(R.xml.preferences);
// get list of available resolutions
Object[] previewSizes = MyFirstAppActivity.camera.getParameters()
.getSupportedPreviewSizes().toArray();
// split object properties into two arrays
String[] ps=new String[previewSizes.length];
for(int i=0;i<previewSizes.length;i++)
{
try
{
int width=((Size)previewSizes[i]).width;
int height=((Size)previewSizes[i]).height;
ps[i]=width+"x"+height;
}
catch(Exception ex)
{}
}
// get list of available resolutions
Object[] recordingSizes = MyFirstAppActivity.camera.getParameters()
.getSupportedPictureSizes().toArray();
// split object properties into two arrays
String[] rs=new String[recordingSizes.length];
for(int i=0;i<recordingSizes.length;i++)
{
try
{
int width=((Size)recordingSizes[i]).width;
int height=((Size)recordingSizes[i]).height;
rs[i]=width+"x"+height;
}
catch(Exception ex)
{}
}
Preference prefPreviewSizes = getPreferenceManager().findPreference("previewSizes");
Preference prefRecordingSizes = getPreferenceManager().findPreference("recordingSizes");
((ListPreference) prefPreviewSizes).setEntries(ps);
((ListPreference) prefRecordingSizes).setEntries(rs);
}
}
Whenever some sort of state change happens (for example, turning off or rotating the screen) the
onCreatemethod gets called.I’m pretty sure what you’re supposed to do is override the
onSaveInstanceStatemethod and save data to it’soutStateBundle, which then gets passed toonCreateas thesavedInstanceStateBundle.For some more info, check out “Handling Runtime Changes” in the Android developer center.
You might be able to keep your camera from causing exceptions by checking if it exists before creating it, something like
or just create a new instance of it in
onCreate