在这里,我有一个代码块,可以将当前活动的信息发送到另一个活动:
@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",即使该值不为空!
在getSharedPreferences("com.amrapps.paneraautomate", MODE_PRIVATE)
和getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
应使用相同字符串作为第一个参数