java - 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);
,但似乎没有任何效果。请帮忙。
解决方案
您应该使用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);
}
推荐阅读
- reactjs - React Native TextInput:为什么secureEntryText会移出输入框并有省略号?
- hadoop - NIFI:使用kafka并将数据存储到hive中的正确方法
- python - 将两个数据框与两个公共列结合起来 - python
- c# - 迷失在界面变化中。接口
没有按预期工作 - c# - C#:从 MSIX 包启动引用的控制台应用程序
- google-apps-script - Google Apps 脚本在夜间自启动
- python - 如何从带有编号网格opencv的图像中提取数字
- google-apps-script - Google Apps 脚本使用 OAuth 和 recaptcha 从网站上抓取数据
- html - 动态 div 列位置
- kubernetes - 数据中心本地 kubernetes 集群中的 Istio 服务网格