如何通过编程将默认值设置为SharedPreferences? [英] How to set a default value to SharedPreferences programmatically?
本文介绍了如何通过编程将默认值设置为SharedPreferences?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用SharedPreferences来保存我的应用程序中需要的有关用户体重的信息.问题是,安装后如何自动设置默认值(例如75 kg)?我知道如何通过.xml做到这一点,但是如何以编程方式做到这一点?
I am using SharedPreferences to keep the information about user's weight, which I need in my application. The problem is, how to set a default value (eg. 75 kg) automatically after installation? I know how to do it via .xml, but how to do this programmatically?
我的代码:
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条件).
For first time use this, or else use your code only(means without if condition).
这篇关于如何通过编程将默认值设置为SharedPreferences?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文