当前位置:  开发笔记 > 编程语言 > 正文

共享首选项不适用于存储/接收数据

如何解决《共享首选项不适用于存储/接收数据》经验,为你挑选了1个好方法。

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

@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",即使该值不为空!



1> Rick Sanchez..:

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

推荐阅读
吻过彩虹的脸_378
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有