简体   繁体   English

Java 代码未在 Android Studio 中开始新活动? 和上下文有关吗?

[英]Java code not starting new activity in Android Studio? Is it to do with the context?

Here is the code:这是代码:

public void check(View button){ //checks if user's username and password correct
    String usernameInput;
    String passwordInput;

    usernameInput = ((EditText)findViewById(R.id.username)).getText().toString(); //gets user inputs as strings
    passwordInput = ((EditText)findViewById(R.id.password)).getText().toString();

    Log.d("username input", usernameInput);
    Log.d("password input", passwordInput);

    if (usernameInput == "user" && passwordInput == "password123") { //checks if correct
        correct(usernameInput);
    }
    else incorrect(button);
}


public void correct(String usernameInput) { //if correct, launches the main activity (main menu) through an intent (see below)
    Intent i = new Intent(this, MainActivity.class);
    i.putExtra("username", usernameInput); //passes data from LoginRegister activity to MainActivity
    startActivity(i);
}

I am trying to create a login system.我正在尝试创建一个登录系统。 Basically, when a button is clicked the 'check' method is called.基本上,当单击按钮时,会调用“检查”方法。 The user inputs from 2 text boxes are checked to see if they're the correct username and password;检查来自 2 个文本框的用户输入以查看它们是否是正确的用户名和密码; if they are, the 'correct' method is called.如果是,则调用“正确”方法。 It works fine up until this point, but for some reason the new activity just is not starting (no errors, it just doesn't start).到目前为止它工作正常,但由于某种原因,新活动没有开始(没有错误,它只是没有开始)。 I have tried putting all sorts for the context in the line Intent i = new Intent(this, MainActivity.class);我已经尝试将各种上下文放在Intent i = new Intent(this, MainActivity.class);行中。 , but nothing seems to work. ,但似乎没有任何效果。 Please help.请帮忙。

You should use equals instead of == .您应该使用equals而不是==

== should be used during reference comparison. ==应在参考比较期间使用。 == checks if both references points to same location or not. ==检查两个引用是否指向相同的位置。 On the other hand, equals() method should be used for content comparison.另一方面, equals()方法应该用于内容比较。 equals() method evaluates the content to check the equality. equals()方法评估内容以检查相等性。

So you should change your code to:因此,您应该将代码更改为:

public void check(View button){ //checks if user's username and password correct
    String usernameInput;
    String passwordInput;

    usernameInput = ((EditText)findViewById(R.id.username)).getText().toString(); //gets user inputs as strings
    passwordInput = ((EditText)findViewById(R.id.password)).getText().toString();

    Log.d("username input", usernameInput);
    Log.d("password input", passwordInput);

    if (usernameInput.equals("user") && passwordInput.equals("password123")) { //checks if correct
        correct(usernameInput);
    }
    else incorrect(button);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM