addListenerForSinglevalueEvent是异步操作。
onDataChange()设置回调后,代码将继续运行,而您尚未获取任何用户名。到您检查mSwitch值时,即使用户名确定,它也始终为false。
要使其正常工作,您应该移动
checkInformation();if(mSwitch) { Intent intent = new Intent(getApplicationContext(), MenuActivity.class); saveUserInformation(); startActivity(intent);}到
onDataChange()回调的末尾。
此外,最好在查询文档之前先检查空字符串和长度。只是为了减少从数据库下载的无用数据。
但是由于for循环,它似乎仍然无法正常工作。像这样尝试:
mSwitch = true; // as its OKfor (DataSnapshot ds : dataSnapshot.getChildren()) { if(name.equals(ds.child("username").getValue(String.class))){ mSwitch = false; Username.setError("Username Taken"); Username.requestFocus(); break; }}...if (mSwitch) startActivity();else showErrorToast();


