该程序第一次创建首选项,但之后它永远不会更改它们.我很感激帮助理解为什么.
这是调用xml的PreferencesScreen.
public class PreferencesScreen extends PreferenceFragment{ private final String TAG = "PreferencesScreen"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG,"OnCreate"); addPreferencesFromResource(R.xml.prefs); }
在首选项中,我有一个ListPreference和一个Preference,它调用一个活动来存储电子邮件.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceCategory android:title="Information Collected"> <ListPreference android:key="loggins" android:title="Logs Stored" android:summary="Choose the top kind of logs do you want to store." android:dialogTitle="Choose Logs" android:entries="@array/logs" android:entryValues="@array/logsValues"/> </PreferenceCategory> <PreferenceCategory android:title="Email Configurations"> <Preference android:key="pushing" android:title="The Email Activity" android:summary="Just push"> <intent android:action = "ADDING_EMAIL"/> </Preference> </PreferenceCategory> </PreferenceScreen>
一切都在这里.问题出在所谓的……
public class AddingEmail extends ListActivity implements OnClickListener{ private Set<String> emails; private EditText emailAdd; SharedPreferences.Editor editor; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.addingemail); Button add = (Button) findViewById(R.id.add); emailAdd = (EditText) findViewById(R.id.email); prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); editor = prefs.edit(); prefList = toArrayList(prefs.getStringSet("emailWrongs",null)); add.setOnClickListener(this); } public void onClick(View v) { Set<String> list = prefs.getStringSet("emailWrongs",null); String newEmail = emailAdd.getText().toString(); if (list==null){ //first time the preferences are called. emails = new TreeSet<String>(); editor.putStringSet("emailWrongs",emails); editor.apply(); } if (newEmail != ""){ emails=prefs.getStringSet("emailWrongs",null); emails.add(newEmail); editor.putStringSet("emailWrongs",emails); editor.apply(); } } }
关键是它总是存储第一次很好,但如果我在添加另一封电子邮件时,首选项不会改变.他们看起来好像改变了,因为如果我打印它们会显示我添加的所有电子邮件,但偏好文件不会改变(在文件资源管理器中检查它).如果我重新启动或关闭并再次打开,则首选项仅包含我添加的第一封电子邮件.
问题是,如果我回到并更改ListPreference的首选项,那么它甚至存储我添加的电子邮件的所有更改.
希望我很清楚,它有很多代码,因为我想要非常明确.
感谢您的帮助.
解决方法
经过一个多星期的寻找错误,我发现了它.
我认为这对很多遇到同样麻烦的人都有帮助.
我认为这对很多遇到同样麻烦的人都有帮助.
问题是,当我调用首选项来获取字符串集时,它只引用列表而不复制它.因此,我必须创建一个新列表并添加之前存储的所有元素,并添加新元素,然后使用编辑器更改新列表的首选项.
代码是这样的:
Set<String> list = prefs.getStringSet("emailWrongs",null); Set<String> newList = new TreeSet<String>(); String newEmail = emailAdd.getText().toString(); if (newEmail != ""){ if (list != null){ for(String each: list){ newList.add(each); } } newList.add(newEmail); editor.putStringSet("emailWrongs",newList); editor.apply(); }