从内存中清除应用时,保存的SharedPreferences更改丢失

时间:2015-05-30 22:56:08

标签: java android sharedpreferences

我正在设置活动中更新并保存SharedPreferences中的值数组。具体来说,来自onCLickListener中的AlertDialog,用于ListView。这些更改似乎保存得很好 - 即在我关闭并重新打开MainActivity后它们仍然完好无损,但只要我的应用程序从内存中释放并重新启动,SharedPreferences就会恢复到之前的状态。

我读到某个地方,在editor.commit()之前调用editor.clear()可以防止这种情况发生,但是这也会删除我的SharedPreferences中的所有其他值(即我没有编辑的那些值)这段代码)。

任何人都可以解释为什么我丢失了我的SharedPreference更新,以及我如何解决这个问题?

代码如下:

final ListView lv = (ListView) findViewById(R.id.list_folders);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {

        // ListView Clicked item index
        int itemPosition = position;

        // ListView Clicked item value
        final String itemValue = (String) lv.getItemAtPosition(position);

        // Ask the user to confirm deletion of the item using an AlertDialog
        AlertDialog.Builder builder = new AlertDialog.Builder(SourceFolders.this);

        builder.setTitle("Confirm");
        builder.setMessage("Remove " + itemValue + "?");

        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // Yes - remove the current item from SharedPreferences
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SourceFolders.this);
                Set<String> set = prefs.getStringSet("source_folders", null);
                if (set == null) {
                    dialog.dismiss(); // List of folders in Preferences is empty - shouldn't happen
                }
                // Remove the selected item from the list
                set.remove(itemValue);
                // Update Shared Preferences
                SharedPreferences.Editor edit = prefs.edit();
                edit.putStringSet("source_folders", set);
                edit.commit();
                folderlist = new ArrayList<String>(set);
                refreshListViewFromPrefs();
                dialog.dismiss();
            }

        });

        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
                dialog.dismiss();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }
});

0 个答案:

没有答案