John John - 1 year ago 107
Android Question

Adding intent code in an if else statement

I'm trying to use the following intent code to add in an if else statement to redirect if login is successful after displaying the toast message under
if (password.equals(storedPassword)) { but I get an "Cannot resolve constructor error.

Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);


if (password.equals(storedPassword)) {
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
dialog.dismiss();


} else {
Toast.makeText(MainActivity.this, "Username or Password incorrect.", Toast.LENGTH_LONG).show();
}
}
});


like this

if (password.equals(storedPassword)) {
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
dialog.dismiss();
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);



} else {
Toast.makeText(MainActivity.this, "Username or Password incorrect.", Toast.LENGTH_LONG).show();
}
}
});



  1. I have an ImageView that is visible in Preview, but is not shown in the emulator. I have already clean/build the project and sync gradle files. What could be the issue?


Answer Source

Do you use this from an anonymous inner class? Then thisrefers to the inner class instead of the activity. Use this instead (like you did with the toasts):

Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download