【问题标题】:Shared preferences saving in memory but not saving to disk共享首选项保存在内存中但不保存到磁盘
【发布时间】:2023-04-09 09:24:01
【问题描述】:

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

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

在应用程序关闭并重新打开之前我可以访问它,这一事实让我认为它存储在内存中而不是存储到磁盘中。

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

我尝试保存的方法是:

  1. 从共享首选项中检索哈希集
  2. 向哈希集添加新字符串
  3. 将更新的哈希集保存在共享首选项中。

代码如下:

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();
}

这就是我在应用程序的其他部分获取存储的哈希集的方式:

// 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>());

提前感谢您的帮助

【问题讨论】:

  • 你确定你使用 context.getSharedPreferences("AppData", Context.MODE_PRIVATE);在 get/set 中?
  • 是的,当然。我编辑了我的问题以包括我在哪里检索它。
  • 我会尝试将默认共享首选项切换为 PreferenceManager.getDefaultSharedPreferences(context) 而不是 context.getSharedPreferences("AppData", Context.MODE_PRIVATE) 除非您有特定理由使用单独的命名共享首选项在您的应用中
  • 感谢尝试,没有任何区别

标签: android sharedpreferences


【解决方案1】:

好的,我找到了原因:

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

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

Android: String set preference is not persistent

我像这样更改了我的存储代码,它工作正常:

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();
    }

感谢大家的帮助

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 是的,我在应用程序中只有两个地方可以访问共享首选项。不,它没有被清除
    • 有时在 android studio 上即时运行会清除每次即时运行的应用数据
    【解决方案3】:

    创建这个类:

    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();
    }
    }
    

    分别使用SetReminderSet(reminderSet)getReminderSet()方法设置或获取值。

    MainActivity:

    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;
    
        }
    }
    }
    

    activity_main.xml:

    <?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>
    

    【讨论】:

    • 即使在关闭应用程序后,我也更新了它赋予价值的代码。好吧,为了简单起见,我使用了这个单独的类,并在一个地方管理所有事情。实际上,commit() 之前的 clear() 方法正在为下次提供价值。我知道 clear() 不是正确的做法,但它正在工作。
    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    相关资源
    最近更新 更多