Android 共享首选项保存在内存中但不保存到磁盘

Android 共享首选项保存在内存中但不保存到磁盘,android,sharedpreferences,Android,Sharedpreferences,我正在尝试编写一个设置为共享首选项的字符串,乍一看它似乎可以工作。在应用程序的其他部分,我可以访问共享首选项并正确读取字符串集 当我离开应用程序时,问题就出现了。共享首选项字符串集中的所有数据都将丢失,并再次返回空集 在应用程序关闭和重新打开之前,我可以访问它,这让我觉得它存储在内存中,而不是存储在磁盘上 我在这里读了很多答案,尝试在提交和应用之间进行切换,但我不知道是什么导致了这个问题 我试图保存它的方式是: 从共享首选项检索哈希集 将新字符串添加到哈希集 将更新的哈希集保存在共享首选项中 代

我正在尝试编写一个设置为共享首选项的字符串,乍一看它似乎可以工作。在应用程序的其他部分,我可以访问共享首选项并正确读取字符串集

当我离开应用程序时,问题就出现了。共享首选项字符串集中的所有数据都将丢失,并再次返回空集

在应用程序关闭和重新打开之前,我可以访问它,这让我觉得它存储在内存中,而不是存储在磁盘上

我在这里读了很多答案,尝试在提交和应用之间进行切换,但我不知道是什么导致了这个问题

我试图保存它的方式是:

  • 从共享首选项检索哈希集
  • 将新字符串添加到哈希集
  • 将更新的哈希集保存在共享首选项中
  • 代码如下:

    public static void storeReminder (Context context, String reminderString){
    
        // Get the set of reminder strings
        SharedPreferences sharedPreferences = context.getSharedPreferences("AppData", Context.MODE_PRIVATE);
        Set <String> remindersStringSet = sharedPreferences.getStringSet(context.getResources().getString(R.string.reminders_hashset_key), new HashSet<String>());
    
        // Add the new reminder string to the reminder string set
        remindersStringSet.add(reminderString);
    
        // Save the reminder string set now that the new reminder string has been added
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putStringSet(context.getResources().getString(R.string.reminders_hashset_key), remindersStringSet);
        editor.commit();
    }
    
    公共静态void存储提醒(上下文上下文、字符串提醒字符串){
    //获取一组提醒字符串
    SharedReferences SharedReferences=context.getSharedReferences(“AppData”,context.MODE\u PRIVATE);
    Set-ReminderStringSet=SharedReferences.getStringSet(context.getResources().getString(R.string.reminders\u hashset\u key),new hashset());
    //将新的提醒字符串添加到提醒字符串集
    添加(提醒字符串);
    //添加新的提醒字符串后,立即保存提醒字符串集
    SharedReferences.Editor=SharedReferences.edit();
    editor.putStringSet(context.getResources().getString(R.string.remenders\u hashset\u key),remendersstringset);
    commit();
    }
    
    这就是我如何在应用程序的其他部分获取存储的哈希集:

    // Get the set of reminder strings
    SharedPreferences sharedPreferences = context.getSharedPreferences("AppData", Context.MODE_PRIVATE);
    Set<String> remindersStringSet = sharedPreferences.getStringSet(context.getResources().getString(R.string.reminders_hashset_key), new HashSet<String>());
    
    //获取提醒字符串集
    SharedReferences SharedReferences=context.getSharedReferences(“AppData”,context.MODE\u PRIVATE);
    Set-ReminderStringSet=SharedReferences.getStringSet(context.getResources().getString(R.string.reminders\u hashset\u key),new hashset());
    

    提前感谢您的帮助

    确保您在打开应用程序(如登录)或其他方法时没有清除共享首选项

    创建此类:

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.preference.PreferenceManager;
    
    import java.util.Set;
    
    public class DemoPrefs {
    private SharedPreferences prefs;
    private SharedPreferences.Editor prefs_edit;
    private static DemoPrefs instance;
    
    public DemoPrefs(Context context) {
        initialize(context);
    }
    
    private void initialize(Context context) {
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
        prefs_edit = prefs.edit();
    }
    
    public static DemoPrefs getInstance(Context context) {
        if (instance == null) {
            instance = new DemoPrefs(context);
        }
        return instance;
    }
    
    public void setReminderSet(Set<String> reminderSet) {
        prefs_edit.putStringSet("reminderSet", reminderSet);
        clear();
        prefs_edit.commit();
    }
    
    public Set<String> getReminderSet() {
        return prefs.getStringSet("reminderSet", null);
    }
    
    public void clear() {
        prefs_edit.clear();
        prefs_edit.commit();
    }
    }
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
    private DemoPrefs prefs;
    private EditText editText;
    private Button button;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialize();
        setListener();
    }
    
    
    private void initialize() {
        prefs = DemoPrefs.getInstance(this);
        editText = (EditText) findViewById(R.id.editText);
        button = (Button) findViewById(R.id.button);
    }
    
    private void setListener() {
        button.setOnClickListener(this);
    }
    
    public void storeReminder(String reminderString) {
        Set<String> reminderSet = null;
        if (prefs.getReminderSet() == null)
            reminderSet = new HashSet<String>();
        else
            reminderSet = prefs.getReminderSet();
        reminderSet.add(reminderString);
        prefs.setReminderSet(reminderSet);
    }
    
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:
                if (!TextUtils.isEmpty(editText.getText().toString().trim())) {
                    if (prefs.getReminderSet() != null)
                        System.out.println("OLD SIZE: " + prefs.getReminderSet().size());
                    storeReminder("Set: " + editText.getText().toString().trim() + "");
                    if (prefs.getReminderSet() != null)
                        System.out.println("NEW SIZE: " + prefs.getReminderSet().size());
                } else {
                    Toast.makeText(this, "Please enter data", Toast.LENGTH_SHORT).show();
                }
                editText.setText("");
                break;
    
        }
    }
    }
    
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.pairroxz.demoapp.MainActivity">
    
    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/button"
        app:layout_constraintTop_toTopOf="parent"
        tools:hint="@string/edit_message" />
    
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:text="@string/button_send"
        app:layout_constraintBaseline_toBaselineOf="@+id/editText"
        app:layout_constraintLeft_toRightOf="@+id/editText"
        app:layout_constraintRight_toRightOf="parent" />
    
    </android.support.constraint.ConstraintLayout>
    
    活动\u main.xml:

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.preference.PreferenceManager;
    
    import java.util.Set;
    
    public class DemoPrefs {
    private SharedPreferences prefs;
    private SharedPreferences.Editor prefs_edit;
    private static DemoPrefs instance;
    
    public DemoPrefs(Context context) {
        initialize(context);
    }
    
    private void initialize(Context context) {
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
        prefs_edit = prefs.edit();
    }
    
    public static DemoPrefs getInstance(Context context) {
        if (instance == null) {
            instance = new DemoPrefs(context);
        }
        return instance;
    }
    
    public void setReminderSet(Set<String> reminderSet) {
        prefs_edit.putStringSet("reminderSet", reminderSet);
        clear();
        prefs_edit.commit();
    }
    
    public Set<String> getReminderSet() {
        return prefs.getStringSet("reminderSet", null);
    }
    
    public void clear() {
        prefs_edit.clear();
        prefs_edit.commit();
    }
    }
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
    private DemoPrefs prefs;
    private EditText editText;
    private Button button;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialize();
        setListener();
    }
    
    
    private void initialize() {
        prefs = DemoPrefs.getInstance(this);
        editText = (EditText) findViewById(R.id.editText);
        button = (Button) findViewById(R.id.button);
    }
    
    private void setListener() {
        button.setOnClickListener(this);
    }
    
    public void storeReminder(String reminderString) {
        Set<String> reminderSet = null;
        if (prefs.getReminderSet() == null)
            reminderSet = new HashSet<String>();
        else
            reminderSet = prefs.getReminderSet();
        reminderSet.add(reminderString);
        prefs.setReminderSet(reminderSet);
    }
    
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:
                if (!TextUtils.isEmpty(editText.getText().toString().trim())) {
                    if (prefs.getReminderSet() != null)
                        System.out.println("OLD SIZE: " + prefs.getReminderSet().size());
                    storeReminder("Set: " + editText.getText().toString().trim() + "");
                    if (prefs.getReminderSet() != null)
                        System.out.println("NEW SIZE: " + prefs.getReminderSet().size());
                } else {
                    Toast.makeText(this, "Please enter data", Toast.LENGTH_SHORT).show();
                }
                editText.setText("");
                break;
    
        }
    }
    }
    
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.pairroxz.demoapp.MainActivity">
    
    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/button"
        app:layout_constraintTop_toTopOf="parent"
        tools:hint="@string/edit_message" />
    
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:text="@string/button_send"
        app:layout_constraintBaseline_toBaselineOf="@+id/editText"
        app:layout_constraintLeft_toRightOf="@+id/editText"
        app:layout_constraintRight_toRightOf="parent" />
    
    </android.support.constraint.ConstraintLayout>
    

    好的,我找到了原因:

    您必须删除存储在存储的首选项中的字符串集,并在其位置添加新的副本

    我在这篇文章的一个答案上找到了它:

    我像这样更改了存储代码,效果很好:

    public static void storeReminder (Context context, String reminderID, String reminderString){
    
            // Get the set of reminder strings
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            Set <String> remindersStringSet = sharedPreferences.getStringSet(context.getResources().getString(R.string.reminders_hashset_key), new HashSet<String>());
    
            // Add the new reminder string to the reminder string set
            remindersStringSet.add(reminderString);
    
            // Get the shared preferences editor
            SharedPreferences.Editor editor = sharedPreferences.edit();
    
            // Delete the current set in shared preferences
            editor.remove(context.getResources().getString(R.string.reminders_hashset_key));
            editor.apply();
    
            // Save the NEW version of reminder string set
            editor.putStringSet(context.getResources().getString(R.string.reminders_hashset_key), new HashSet<String>(remindersStringSet));
            editor.apply();
        }
    
    publicstaticvoidstorerementer(上下文上下文、字符串提醒ID、字符串提醒字符串){
    //获取一组提醒字符串
    SharedReferences SharedReferences=PreferenceManager.GetDefaultSharedReferences(上下文);
    Set-ReminderStringSet=SharedReferences.getStringSet(context.getResources().getString(R.string.reminders\u hashset\u key),new hashset());
    //将新的提醒字符串添加到提醒字符串集
    添加(提醒字符串);
    //获取共享首选项编辑器
    SharedReferences.Editor=SharedReferences.edit();
    //删除共享首选项中的当前集
    remove(context.getResources().getString(R.string.remementers\u hashset\u key));
    editor.apply();
    //保存提醒字符串集的新版本
    putStringSet(context.getResources().getString(R.string.rementers\u hashset\u key),new hashset(rementersstringset));
    editor.apply();
    }
    

    谢谢大家的帮助

    您确定要使用context.getSharedReferences(“AppData”,context.MODE\u PRIVATE)吗;在两个get/set中?是的,当然。我编辑了我的问题以包括检索它的位置。我将尝试切换到默认共享首选项作为PreferenceManager.GetDefaultSharedReferences(上下文),而不是context.GetSharedReferences(“AppData”,context.MODE_PRIVATE)除非您有特定的理由在应用程序中使用单独的命名共享首选项,否则这没有任何区别是的,我在应用程序中只有两个位置访问共享首选项。不,它没有被清除有时android studio上的instant run会清除每个instant run的应用程序数据,即使在关闭应用程序后,我也会更新它赋予价值的代码。为了简单起见,我使用了这个单独的类,并在一个地方管理所有的事情。实际上,commit()之前的clear()方法正在为下次提供值。我知道这不是做clear()的正确方法,但它正在起作用。