2017-07-31 182 views
0

我使用下面的方法来保存和读取用户设置:设置sharedpreferences默认值

private void saveUserSettings(){ 
    SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = userSettings.edit(); 
    editor.putInt("timeOne",timeOne); 
    editor.apply(); 
} 

private int getUserSettings(){ 
     SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE); 
     timeOne = userSettings.getInt("timeOne",timeOne);  
    } 

然后在的onCreate如下:

SharedPreferences prefs = getSharedPreferences("userSettings", Context.MODE_PRIVATE); 

这是罚款和数据保存时应用程序重新启动。不过,我希望在最初安装应用程序时拥有默认数据,它似乎应该将值存储在xml文件中。

我创建在以下文件RES/XML /的preferences.xml

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 
    <EditTextPreference 
     android:key="timeOne" 
     android:defaultValue="2"/> 
</PreferenceScreen> 

然后在的onCreate:

PreferenceManager.setDefaultValues(this, R.xml.preferences, false); 

我改变了 “userSettings” 喜好投其所好,但这多申不工作并返回零值。这种阅读xml文件的方法是否正确或/我能忽略一些东西?

回答

1

我觉得你太过复杂了。

在此说明中,如果没有与该名称共享的首选项,则使用默认的第二个参数。

您只需将该值设置为您需要的默认值即可。

timeOne = userSettings.getInt("timeOne",<Put here the default value>); 

编辑我

比方说默认值,如果它是第一次应用程序运行并没有尚未保存的设置,为2

读取值的方法应该是这样的。

private int getUserSettings(){ 
     SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE); 
     timeOne = userSettings.getInt("timeOne",2);  
} 
+0

这是一个公平点,但问题是从preference.xml文件读取。当它应该是2时,它返回0。 – MXG123

+0

如果2是默认值,那么为什么不把它设置为这样呢? timeOne = userSettings.getInt(“timeOne”,2); – Juan

+0

我已经在Edit I – Juan