【问题标题】:How to store two value separately in sharedPreferences?如何在 sharedPreferences 中分别存储两个值?
【发布时间】:2016-09-22 21:57:37
【问题描述】:

我有两个带有EditText 的alertDialog,每个都应该保存一个值以存储在sharedPreferences 中。但似乎不是单独存储它们,而是将第一个输入值替换为第二个输入值。这是我的代码:

public void IPconfig(){

        // some AlertDialog Builder codes

        sharedPreferences = getSharedPreferences("FirstText", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                editor.putString("FirstText", etIP.getText().toString());
                editor.apply();
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });

        builder.create().show();
    }

    public void MonitoringIPConfig(){

        // some AlertDialog Builder codes

        sharedPreferences = getSharedPreferences("SecondText", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                editor.putString("SecondText", etIP.getText().toString());
                editor.apply();
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });

        builder.create().show();
    }

【问题讨论】:

  • 您在两种方法之间重复使用 AlertDialog.Builder 实例,这可能是您的问题的原因。每个方法都应该创建自己的AlertDialog.Builder

标签: android sharedpreferences


【解决方案1】:

您必须调用 commit() 才能使您在编辑器中执行的任何更改实际显示在 SharedPreferences 中,正如 Android 开发者页面所建议的那样。 https://developer.android.com/reference/android/content/SharedPreferences.html

尝试以下方法:

editor.putString("FirstText", etIP.getText().toString()).commit();

【讨论】:

  • 看起来不是问题所在,OP 正在调用 apply()
  • 注意到了。但是最近即使我有apply(),我的代码也不起作用。当我将其更改为commit() 时,它运行良好。我什至不知道为什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 2018-06-13
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
相关资源
最近更新 更多