问题是我将设置保存在一个Activiti
中final CheckBox semester=(CheckBox)layout.findViewById(R.id.chbSemeseter);
Context context = getApplicationContext();
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor=preferences.edit();
final Calendar calendar=Calendar.getInstance();
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Select current week and semester!");
builder.setPositiveButton("First Week",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (semester.isChecked()){
int week=calendar.get(Calendar.WEEK_OF_YEAR);
editor.putInt(APP_PREFERENCES_SEMESTER,week);
editor.putInt(APP_PREFERENCES_SEMESTER,1);
editor.commit();
} else {
int week=calendar.get(Calendar.WEEK_OF_YEAR);
editor.putInt(APP_PREFERENCES_SEMESTER,week);
editor.putInt(APP_PREFERENCES_SEMESTER,2);
editor.commit();
}
}
});
但是当我尝试在另一个活动中使用它时,我收到错误
Context context = getApplicationContext();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences.contains(ActivitySetting.APP_PREFERENCES_WEEK)){
String t=preferences.getInt(ActivitySetting.APP_PREFERENCES_WEEK,0)+"";
MyLog.d("Now week "+t);
}else {
MyLog.d("NOt preferences");
}
错误日志:
//Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Integer
at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:240)
at com.example.Journal.UI.ActivityLiveDiscipline.onCreate
如何在一个活动中保存首选项并在另一个活动中使用?
答案 0 :(得分:0)
您似乎设置了APP_PREFERENCES_SEMESTER设置,但是您读取了APP_PREFERENCES_WEEK设置。您应该使用相同的名称。
答案 1 :(得分:0)
你使用不同整数值的相同键所以制作不同的键如下
builder.setPositiveButton("First Week",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (semester.isChecked()){
int week=calendar.get(Calendar.WEEK_OF_YEAR);
editor.putInt(APP_PREFERENCES_SEMESTER_WEEK,week);
editor.putInt(APP_PREFERENCES_SEMESTER,1);
editor.commit();
} else {
int week=calendar.get(Calendar.WEEK_OF_YEAR);
editor.putInt(APP_PREFERENCES_SEMESTER_WEEK,week);
editor.putInt(APP_PREFERENCES_SEMESTER,2);
editor.commit();
}
}
});
在另一个Activity中使用:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
int intweek = preferences.getInt(APP_PREFERENCES_SEMESTER_WEEK, 0);
int intextra = preferences.getInt(APP_PREFERENCES_SEMESTER, 0);
还有一件事不需要这样做:
if (preferences.contains(ActivitySetting.APP_PREFERENCES_WEEK))
因为如果没有设置Prefrance,那么它会给你0。