繁体   English   中英

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

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

这是代码:

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);
}

我正在尝试创建一个登录系统。 基本上,当单击按钮时,会调用“检查”方法。 检查来自 2 个文本框的用户输入以查看它们是否是正确的用户名和密码; 如果是,则调用“正确”方法。 到目前为止它工作正常,但由于某种原因,新活动没有开始(没有错误,它只是没有开始)。 我已经尝试将各种上下文放在Intent i = new Intent(this, MainActivity.class);行中。 ,但似乎没有任何效果。 请帮忙。

您应该使用equals而不是==

==应在参考比较期间使用。 ==检查两个引用是否指向相同的位置。 另一方面, equals()方法应该用于内容比较。 equals()方法评估内容以检查相等性。

因此,您应该将代码更改为:

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