我编写了我的第一个 Android 应用程序,并且对 Android 开发(以及 Java)非常陌生。我有 PreferenceActivity 并注意到当显示活动并关闭移动设备时,它的 onCreate() 再次被调用。更令人困惑的是静态成员MyFirstAppActivity.camera
不再存在导致异常。我可以在那里检查 null 但我想知道为什么会发生这种情况以及避免它的最佳方法是什么?
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);
}
}