gpt4 book ai didi

android - 共享偏好阅读值返回默认值

转载 作者:搜寻专家 更新时间:2023-11-01 08:03:26 25 4
gpt4 key购买 nike

我想我在从 SharedPreferences 中检索值时遗漏了一些东西。

我的代码:

public class SecondActivity extends Activity {

private TextView password;
private EditText username;
private Button button;
private String name;
private String pass;
private Set<String> set;
private TextView show;
SharedPreferences myPrefs;
SharedPreferences.Editor editor;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);

myPrefs = this.getPreferences(MODE_PRIVATE);
editor = myPrefs.edit();

username = (EditText) findViewById(R.id.editText1);
password = (EditText) findViewById(R.id.editText2);
button = (Button) findViewById(R.id.button1);
show = (TextView) findViewById(R.id.textView3);

name = username.getText().toString();
pass = password.getText().toString();

/*
* set = new HashSet<String>(); set.add(name); set.add(pass);
*/

}

public void saveToPreference(View v) {

editor.putString("UserName", name);
editor.putString("Password", pass);
editor.commit();

SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String use = myPref.getString("UserName", "Sorry");
String pas = myPref.getString("Password", "SorryAgain");
Toast.makeText(getApplicationContext(), use, Toast.LENGTH_SHORT).show();
show.append(use + "\n" + pas);

}

}

应用程序不会强制/关闭。相反,我得到了 defaultValues;从 SharedPreferences 中检索“Sorry”、“SorryAgain”。 “对不起”被吐槽了。

我还应该做什么?

最佳答案

您正在修改返回的 preferences:

this.getPreferences(MODE_PRIVATE);

然后您正在阅读由以下人员返回的首选项:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

您应该在 onCreate 中初始化 myPrefs,然后在所有 Activity 函数中使用该实例,以确保您使用的是完全相同的 SharedPreferences。像这样:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);

myPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = myPrefs.edit();


username = (EditText)findViewById(R.id.editText1);
password = (EditText)findViewById(R.id.editText2);
button = (Button)findViewById(R.id.button1);
show = (TextView)findViewById(R.id.textView3);

}


public void saveToPreference(View v){

editor.putString("UserName",username.getText().toString());
editor.putString("Password", password.getText().toString());
editor.commit();

String use = myPrefs.getString("UserName", "Sorry");
String pas = myPrefs.getString("Password", "SorryAgain");
Toast.makeText(getApplicationContext(), use,Toast.LENGTH_SHORT).show();
show.append(use+"\n"+ pas);


}

关于android - 共享偏好阅读值返回默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17786061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com