[英]NullPointerException when activity starts and checkbox is not checked
[英]Quit showing an Activity when CheckBox is checked
我有一个带有“不再显示”复选框的DialogActivity。
我需要它做的就像CheckBox所说的一样。 选中CheckBox后,无论应用程序是重新启动还是终止,都不必再向用户显示“活动”。
public class PopUpInfoActivity extends Activity {
static final String PREFS = "preference_file";
@Override
public void onCreate(Bundle state) {
setContentView(R.layout.popupinfo_layout);
CheckBox chk = (CheckBox) findViewById(R.id.dontshow_checkbox);
chk.setChecked(PreferenceManager.getDefaultSharedPreferences(this).getBoolean("value", false));
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//store isChecked to Preferences
SharedPreferences settings = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isChecked", false);
PreferenceManager.getDefaultSharedPreferences(PopUpInfoActivity.this).edit().putBoolean("value", isChecked).apply();
}
});
Intent intent = new Intent(PopUpInfoActivity.this, ChordsListActivity.class);
if (!chk.isChecked()) {
// run activity
super.onCreate(state);
} else {
startActivity(intent);
}
}
}
如果我这样做,应用程序将崩溃。
如果我将else替换为:
else {
onStop()
}
该代码无法正常工作。
如果您能帮助我解决此问题,我将不胜感激!
编辑:这是我在ChordsListActivity
获得的ChordsListActivity
,它是调用PopUpInfoActivity
的活动,但我没有得到应放在if()
语句中的内容。
Intent legendaIntent = new Intent(ChordsListActivity.this, PopUpInfoActivity.class);
if(/*what's here?*/)
startActivity(legendaIntent);
在该MainActivity中,读取您的首选项键(Show_Dialog),如果为true,则启动PopUpInfoActivity,否则启动ChordsListActivity。
逻辑应该在母亲活动中
在PopUpInfoActivity中,仅当用户签出ChekBox时,才应将首选项键编辑为false。
为此,请在res / xml下创建一个preferences.xml文件,在该文件中,您必须创建一个密钥(布尔值),并将其存储在PopUpInfoActivity.Checkbox状态下,默认值为(真)。
这是一个例子
<CheckBoxPreference
android:key="Show_Dialog"
android:defaultValue="true" />
您应该从MainActivity中读取以下值:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Boolean showDlg = sharedPref.getBoolean("Show_Dialog", true);
如果showDlg为true,则弹出对话框,否则继续您要执行的操作。
当然,如果用户选中了该复选框,则需要更改Show_Dialog的值,您可以这样做:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor preferencesEditor = sharedPref.edit();
preferencesEditor.putBoolean("Show_Dialog", false);
preferencesEditor.commit();
这样,您可以确保下次用户启动您的应用程序时,您的主要活动将Show_Dialog读取为false
祝好运
首先, super.onCreate()
必须是任何Activity的onCreate()
的第一个调用。
其次,将SharedPrefence
的值存储在布尔值中,而不是直接设置CheckBox
,并在setContentView()
之前使用它来完成当前的Activity
并启动下一个(如果为true)。 如果没有,请继续处理UI内容以及您需要的其他任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.