首页 > 解决方案 > Java 代码没有在 Android Studio 中启动新活动?和上下文有关吗?

问题描述

这是代码:

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 个文本框的用户输入以查看它们是否是正确的用户名和密码;如果是,则调用“正确”方法。到目前为止它工作正常,但由于某种原因,新活动没有开始(没有错误,它只是没有开始)。我已经尝试在 line 中放置各种上下文Intent i = new Intent(this, MainActivity.class);,但似乎没有任何效果。请帮忙。

标签: javaandroidandroid-studioandroid-intentandroid-activity

解决方案


您应该使用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);
}


推荐阅读