【问题标题】:Shared Preferences not working for storing/receiving data共享首选项不适用于存储/接收数据
【发布时间】:2015-12-16 19:39:13
【问题描述】:

这里有一段代码可以将当前活动的信息发送到另一个活动:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tutorial);

        prefs = getSharedPreferences("com.amrapps.paneraautomate", MODE_PRIVATE);

        name = (EditText) findViewById(R.id.name);
        lastName = (EditText) findViewById(R.id.lastName);
        password = (EditText) findViewById(R.id.password);
        final CheckBox passwordReveal = (CheckBox) findViewById
                (R.id.checkbox);

        passwordReveal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {
                    password.setInputType(129);
                }
            }
        });
    }

    public void continueButton(View v) {
        String stringName = name.getText().toString();
        String stringLastName = lastName.getText().toString();
        String stringPassword = password.getText().toString();

        SharedPreferences.Editor editor = prefs.edit();
        prefs.edit().putString("name", stringName).commit();
        prefs.edit().putString("lastName", stringLastName).commit();
        prefs.edit().putString("password", stringPassword);
        editor.commit();

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

我正在尝试使用在 MainActivity 中输入的数据,如下所示:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);

        name = prefs.getString("name", "");
        lastName = prefs.getString("lastName", "");
        password = prefs.getString("password", "");

        // Check for null values and set default if empty
        if (name == "") {
            name = "Johnny";
        }

        if (lastName == "") {
            lastName = "Appleseed";
        }

        if (password == "") {
            password = "Asdf123";
        }

不幸的是,每次运行时它总是将名称设置为“Johnny Appleseed”,即使值不为空!

【问题讨论】:

  • 第一件事是,您正在使用两个不同的首选项文件。接下来就是you are comparing Strings incorrectly
  • 天哪,你是对的!这太尴尬了,因为我们刚刚在我的 AP 计算机科学课上了解了最后一章...... :'(

标签: android


【解决方案1】:

getSharedPreferences("com.amrapps.paneraautomate", MODE_PRIVATE) 和getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE); 应该使用与第一个参数相同的字符串

【讨论】:

  • 哇。我觉得很愚蠢:P。此外,正如上面发布的评论者,我错误地比较了字符串。
猜你喜欢
  • 2015-10-17
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 2022-08-15
  • 2017-07-29
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
相关资源
最近更新 更多