Passing data from one activity to another and then printing

Brett :

The problem I am having is that it prints out Null on the second activity and not the actual username that is entered. Is the data being passed to the second activity correctly? Does the second activity need more code? Sorry but not the best at programming.

I have this code in my main class

if (username.getText().toString().equals("batman") &&
password.getText().toString().equals("Joker")) { 
Toast.makeText(MainActivity.this, "Username and 
password is correct", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.example.*******.loginpage.User");
intent.putExtra("username",String.valueOf(username));
startActivity(new Intent(MainActivity.this, User.class));

This is the code inside my second class.

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

Intent intent = getIntent();
String username = getIntent().getStringExtra("username");

TextView textView = (TextView) findViewById(R.id.textView4);
textView.setText("Welcome" + " " + username );
Randyka Yudhistira :

The problem is your intent in your first class

Intent intent = new Intent("com.example.*******.loginpage.User"); <-- have created an intent
intent.putExtra("username",String.valueOf(username));
startActivity(new Intent(MainActivity.this, User.class)); <-- but using new Intent

You have created an intent but you passing new intent. Use your created Intent instead of passing new Intent.

Intent intent = new Intent(MainActivity.this, User.class);
intent.putExtra("username",String.valueOf(username));
startActivity(intent);

EDIT

Instead using String.valueOf(username) you must use username.getText(), because String.valueOf(username) is method to translate your object to String.

Intent intent = new Intent(MainActivity.this, User.class);
intent.putExtra("username",username.getText());
startActivity(intent);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115289&siteId=1