1

I am a noob developer in android who is just learning to experiment with activities and stuff like that. Today I learnt about TextFields, and tried to use a normal plaintext EditText view as a username, a password-input type EditText view, and a button to which an onClick method by the name of "loginMethod" was attached. I used simple if-else statements by taking the inputs in the text fields to string and want to open a new activity when the desired username and password are entered, and to show a toast if not. However, on running the application it only gives the toast message for the error and doesn't start the activity.

The code for the method is attached below:

public void loginMethod(View view)
    {
        EditText username=(EditText) findViewById(R.id.username);
        EditText password=(EditText) findViewById(R.id.password);
        String user_name=username.getText().toString();
        String pass_word=password.getText().toString();
        Log.i("Info","Entered username: "+user_name+" and Entered password: "+pass_word);
        Context context=getApplicationContext();
        int duration= Toast.LENGTH_LONG;
        if (user_name=="myuser" && pass_word == "mypass")
        {
            Intent i=new Intent(MainActivity.this,welcome.class);
            startActivity(i);
        }
        else Toast.makeText(getApplicationContext(),"Wrong Username or Password!",duration).show();
    }

The output when the image is run is also attached in the image below. Please help. Check out the output screenshot from here

090
  • 97
  • 10

1 Answers1

0

Change this line:

if (user_name.text.toString()=="myuser" && pass_word.text.toString() == "mypass")
MMG
  • 3,226
  • 5
  • 16
  • 43
  • Thanks, but as the user above mentioned, we can't compare strings using ```==``` in Java. I used ```user_name.equals(myuser)``` and that worked. Nevertheless, thanks! <3 – 090 Apr 07 '20 at 07:27
  • if my code works correctly, you can check it as correct answer.@SanskarUpadhyay – MMG Apr 07 '20 at 07:29
  • Try this simple code to see we can compare two strings with == operator @Sanskar – MMG Apr 07 '20 at 07:38
  • public class HelloWorld{ public static void main(String []args){ String a="abcd"; String b="abcd"; if(a==b) System.out.println("Hello World"); } }@Sanskar – MMG Apr 07 '20 at 07:38