简体   繁体   English

检查字符串为NULL还是EMPTY

[英]Check String is NULL or EMPTY

Hi I understand there are duplicates like ( Firebase Registration, Given String is empty or null ) and ( I keep getting"java.lang.IllegalArgumentException: Given String is empty or null" and it has something to do with auth = FirebaseAuth.getInstance();" ). 嗨,我知道有重复的内容,例如( Firebase注册,给定的字符串为空或null )和( 我一直在获取“ java.lang.IllegalArgumentException:给定的字符串为空或null”,这与auth = FirebaseAuth.getInstance( );“ )。

Both articles mentioned solution about the api_key. 这两篇文章都提到了有关api_key的解决方案。 I have checked mine and they were already exist so I strongly believe it is no longer due to that. 我已经检查了我的地雷,它们已经存在,所以我坚信它不再是这个原因。 As such I researched further and found out that I need to have something to check empty so I got these ( Check whether a string is not null and not empty ) and ( Checking if a string is empty or null in Java ). 这样,我进行了进一步研究,发现我需要检查一下是否为空,因此得到了这些内容( 检查字符串是否不为null且不为空 )和( 检查Java中的字符串为空还是null )。

I did tried their solutions but to no avail - I am still getting the above-mentioned error. 我确实尝试了他们的解决方案,但无济于事-我仍然遇到上述错误。 I coded it using my instincts and the guides given but I am still not entirely sure if I did it right or not. 我使用自己的直觉和给出的指南对其进行了编码,但是我仍然不确定是否正确。 As in, whether the mistakes are the codes itself or I placed them wrongly. 就像错误一样,无论错误是代码本身还是我错误地放置了它们。

Can anyone help me to check and provide guidance so I can correct the mistake? 谁能帮助我检查并提供指导,以便我纠正错误? NOTE: I'm using Firebase for authentication. 注意:我正在使用Firebase进行身份验证。

Below are my codes: 以下是我的代码:

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

} }

Error trace 错误跟踪

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)

Be careful with getText() . 使用getText()要小心。 You need to check the result of getText() , and not the subsequent toString() : 您需要检查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
}

This is because, for whatever reason, if getText() is null , then toString() is called on the EditText instance itself, which will return the full classname of EditText and that instance's hashcode. 这是因为无论出于何种原因,如果getText()null ,则在EditText实例本身上调用toString() ,这将返回EditText的完整类名以及该实例的哈希码。

Also, you should be calling the result of checkEmptyCredentials() before you call validate() , not after you attempt the login. 此外,您应该呼吁的结果checkEmptyCredentials()调用之前 validate()而不是之后尝试登录。 This is likely the cause of your crash, while the above will fix an error you haven't yet run into. 这可能是导致崩溃的原因,而以上内容将修复您尚未遇到的错误。

firebaseAuth.signInWithEmailAndPassword function does not allow null or empty text. firebaseAuth.signInWithEmailAndPassword函数不允许使用null或空文本。 So you have to make sure that these fields are not null & not empty. 因此,您必须确保这些字段不为null和不为空。

For easier check, i suggest you using this class https://developer.android.com/reference/android/text/TextUtils . 为了便于检查,我建议您使用此类https://developer.android.com/reference/android/text/TextUtils It has a function isEmpty() which can check null and empty in 1 call. 它具有一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM