[英]Check String is NULL or EMPTY
嗨,我知道有重復的內容,例如( Firebase注冊,給定的字符串為空或null )和( 我一直在獲取“ java.lang.IllegalArgumentException:給定的字符串為空或null”,這與auth = FirebaseAuth.getInstance( );“ )。
這兩篇文章都提到了有關api_key的解決方案。 我已經檢查了我的地雷,它們已經存在,所以我堅信它不再是這個原因。 這樣,我進行了進一步研究,發現我需要檢查一下是否為空,因此得到了這些內容( 檢查字符串是否不為null且不為空 )和( 檢查Java中的字符串為空還是null )。
我確實嘗試了他們的解決方案,但無濟於事-我仍然遇到上述錯誤。 我使用自己的直覺和給出的指南對其進行了編碼,但是我仍然不確定是否正確。 就像錯誤一樣,無論錯誤是代碼本身還是我錯誤地放置了它們。
誰能幫助我檢查並提供指導,以便我糾正錯誤? 注意:我正在使用Firebase進行身份驗證。
以下是我的代碼:
package com.example.run_h.boav2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.hardware.usb.UsbRequest;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private EditText Username;
private EditText Password;
private TextView Info;
private Button Login;
private int counter = 3;
private Button userRegistration;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private TextView forgotPassword;
String name, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Username = (EditText)findViewById(R.id.etUsername);
Password = (EditText)findViewById(R.id.etPassword);
Info = (TextView)findViewById(R.id.tvInfo);
Login = (Button)findViewById(R.id.btnLogin);
userRegistration = (Button)
findViewById(R.id.tvRegister);
forgotPassword =
(TextView)findViewById(R.id.tvForgotPassword);
Info.setText("# of Attempts Left: 3");
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
progressDialog = new ProgressDialog(this);
//user has logged in and never once logged out. auto
bring to the secondactivity (dashboard) page.
if(user != null){
finish();
startActivity(new Intent(MainActivity.this,
SecondActivity.class));
}
Login.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
validate(Username.getText().toString(),
Password.getText().toString());
}
});
userRegistration.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,
RegistrationActivity.class));
}
});
forgotPassword.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,
PasswordActivity.class ));
}
});
}
private void validate(String userName, String
userPassword){
progressDialog.setMessage("Please hold on. We are
testing your patience!");
progressDialog.setProgressStyle(progressDialog.STYLE_SPINNER);
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(userName,
userPassword).addOnCompleteListener(new
OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult>
task) {
if(task.isSuccessful()){
progressDialog.dismiss();
checkEmailVerification();
}
else{
//Toast.makeText(MainActivity.this, "Login failed.
Incorrect username or password. Please try again.",
Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
checkEmptyCredentials();
counter--;
Info.setText("# of Attempts Left: " + counter);
if(counter == 0){
Login.setEnabled(false);
startActivity(new Intent(MainActivity.this, PasswordActivity.class)); //forces user to reset password
}
}
}
});
}
private Boolean checkEmptyCredentials(){
Boolean result = false;
name = Username.getText().toString();
password = Password.getText().toString();
if(name != null && name.isEmpty() || password != null && password.isEmpty()){
Toast.makeText(this, "All fields must not be blank.", Toast.LENGTH_SHORT).show();
}else{
result = true;
}
return result;
}
private void checkEmailVerification(){
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Boolean emailflag = firebaseUser.isEmailVerified();
if(emailflag){
finish();
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}else{
Toast.makeText(this, "Please verify your email and account to login.", Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
}
}
}
錯誤跟蹤
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.run_h.boav2, PID: 27092
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(Unknown Source)
at com.example.run_h.boav2.MainActivity.validate(MainActivity.java:89)
at com.example.run_h.boav2.MainActivity.access$200(MainActivity.java:21)
at com.example.run_h.boav2.MainActivity$1.onClick(MainActivity.java:64)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
使用getText()
要小心。 您需要檢查getText()
的結果,而不是隨后的toString()
:
CharSequence text = someEditText.getText();
if (text == null) {
//do what you do when the text is null or empty
}
String stringText = text.toString();
if (stringText.isEmpty()) {
//do what you do when the text is null or empty
}
這是因為無論出於何種原因,如果getText()
為null
,則在EditText實例本身上調用toString()
,這將返回EditText的完整類名以及該實例的哈希碼。
此外,您應該呼吁的結果checkEmptyCredentials()
調用之前 validate()
而不是之后嘗試登錄。 這可能是導致崩潰的原因,而以上內容將修復您尚未遇到的錯誤。
firebaseAuth.signInWithEmailAndPassword
函數不允許使用null或空文本。 因此,您必須確保這些字段不為null和不為空。
為了便於檢查,我建議您使用此類https://developer.android.com/reference/android/text/TextUtils 。 它具有一個isEmpty()
函數,可以在一次調用中檢查null和empty。
private void validate(String userName, String userPassword){
if (TextUtils.isEmpty(userName)) return; // userName null or empty. We do not process it.
if (TextUtils.isEmpty(userPassword)) return; // userPassword null or empty. We do not process it.
progressDialog.setMessage("Please hold on. We are
testing your patience!");
progressDialog.setProgressStyle(progressDialog.STYLE_SPINNER);
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(userName,
userPassword).addOnCompleteListener(new
OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult>
task) {
if(task.isSuccessful()){
progressDialog.dismiss();
checkEmailVerification();
}
else{
//Toast.makeText(MainActivity.this, "Login failed.
Incorrect username or password. Please try again.",
Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
//checkEmptyCredentials(); //We need to check before signin. So you can replace my code lines above with this function.
counter--;
Info.setText("# of Attempts Left: " + counter);
if(counter == 0){
Login.setEnabled(false);
startActivity(new Intent(MainActivity.this, PasswordActivity.class)); //forces user to reset password
}
}
}
});
}
if (!password.getText().toString().isEmpty()&&!email.getText().toString().isEmpty()) {
firebaseAuth.signInWithEmailAndPassword(name, password).addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
// there was an error
Toast.makeText(Login.this, "Something Went wrong", Toast.LENGTH_SHORT).show();
} else {
checkEmailVerification();
} }
});
}
} else {
Toast.makeText(this, "All fields must not be blank.", Toast.LENGTH_SHORT).show();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.