Reputation: 399
Here I have a block of code that sends information from the current activity to another one:
@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);
}
I am trying to use the data entered there in my MainActivity like so:
@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";
}
Unfortunately, every time it runs it always sets the name to "Johnny Appleseed" even if the value is not null!
Upvotes: 0
Views: 257
Reputation: 4766
The getSharedPreferences("com.amrapps.paneraautomate", MODE_PRIVATE)
and getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
should use the same string as the first parameter
Upvotes: 5