I'm currently trying to program an app which requires the user to key in their name. This is the "Login" page.
public class Login extends Activity {
EditText username;
@Override
public void onCreate(Bundle savedInstanceState)
{
username = (EditText)findViewById(R.id.username);
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button loginButton = (Button) findViewById(R.id.loginBtn);
loginButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent("com.example.MainActivity");
Bundle extras = new Bundle();
extras.putString("name", username.getText().toString());
intent.putExtras(extras);
startActivity(intent);
}
});
}
protected void onDestroy() {
super.onDestroy();
}
protected void onPause() {
super.onPause();
saveAsPreferences();
}
protected void onRestart() {
super.onRestart();
saveAsPreferences();
}
protected void onResume() {
super.onResume();
retrievePreferences();
}
protected void onStart() {
super.onStart();
retrievePreferences();
}
protected void onStop() {
super.onStop();
saveAsPreferences();
}
public void saveAsPreferences()
{
SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
String Name = username.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", Name);
editor.commit();
}
public void retrievePreferences()
{
SharedPreferences prefs = getSharedPreferences("preferences",MODE_PRIVATE);
if(prefs.contains("name"))
{
String Name = prefs.getString("name", "");
username.setText(Name);
}
}
}
and this is my Result page
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
String Name = bundle.getString("name");
TextView welcomeUser = (TextView) findViewById(R.id.welcomeUser);
welcomeUser.setText("Hello " + Name + "!");
}
why isn't my codes working? Thanks! Note: I've linked the pages correctly before I start on passing data.