我正在使用 SharedPreferences 来保存我的应用程序中需要的有关用户体重的信息。问题是,如何在安装后自动设置一个默认值(例如75公斤)?我知道如何通过 .xml 执行此操作,但如何以编程方式执行此操作?
我的代码:
public class SettingsDialogFragment extends DialogFragment{
public static final String PREFS_NAME = "settings";
public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Data.weight = weight;
SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_NAME, 0);
Editor editor = prefs.edit();
editor.putInt("key_weight", weight);
editor.commit();
Data.ifMale = ifMale;
checkedRadio = rg.getCheckedRadioButtonId();
System.out.println("numer radio" +checkedRadio);
}
});
return builder.create();
}
}
最佳答案
请尝试这种方式。
SharedPreferences prefs = getActivity().getSharedPreferences(
PREFS_NAME, 0);
if (prefs.getInt("key_weight", null) == null) {
Editor editor = prefs.edit();
editor.putInt("key_weight", 75);
editor.commit();
}
第一次使用这个,或者仅使用您的代码(意味着没有 if 条件)。
关于android - 如何以编程方式设置 SharedPreferences 的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26765376/