Firebase访问无效

时间:2017-12-27 18:26:44

标签: android firebase firebase-authentication

所以,事情是我按照Firebase设置中的所有步骤操作,但控件没有按照我的createUserWithEmailAndPassword()方法移动。屏幕刚冻结,除了progressBar进入圈子外没有任何其他事情发生。

这是我的gradle build.app文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.example.parma.gareebcalculator"
        minSdkVersion 23
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

    implementation 'com.google.firebase:firebase-auth:11.0.4'
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:support-v4:26.1.0'

    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

这是我的代码: -

public class RegsiterPage extends AppCompatActivity implements View.OnClickListener{

    private EditText userName;
    private EditText email;
    private EditText password;
    private EditText repassword;
    private Button signUp;
    private ProgressBar progressBar;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_regsiter_page);

        userName = (EditText) findViewById(R.id.usernameid);
        email = (EditText) findViewById(R.id.emailid);
        password = (EditText) findViewById(R.id.passwordid);
        repassword = (EditText) findViewById(R.id.repasswordid);
        signUp = (Button) findViewById(R.id.signupid);
        progressBar = (ProgressBar) findViewById(R.id.progressBarid);
        // Used to intialize the firebase object and register the user on the server:-
        mAuth = FirebaseAuth.getInstance();

        signUp.setOnClickListener(this);
    }

    //Email constraints:-
    //To check whether the entered email is of correct format:
    private boolean isValidEmail(String email)
    {
        if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
        {
            return false;
        }
        return true;
    }

    //Username constraints:-
    //To check whether the given username only contains letters or digits:
    private boolean userNameCheck(String name){
        if(Character.isDigit(name.charAt(0))){
            return  false;
        }
        for(int i=0;i<name.length();i++){
            if(!Character.isLetterOrDigit(name.charAt(i))){
                return false;
            }
        }
        return true;
    }

    private boolean checkUserNameLength(String name){
        if(name.length()<8){
            return false;
        }
        return true;
    }

    //Password constraints:-
    //To see whethter the password contains any special characters or not:
    private boolean checkSpecial(String pass){
        byte[] bytes = pass.getBytes();
        for(byte temp:bytes){
            if(temp>=33 && temp<=47){
                return false;
            }
        }
        return true;
    }

    //To see whethter the password is containing both alphabets and numbers:
    private boolean checkPassword(String pass){
        if(pass.length()<8){
            return false;
        }
        for(int i=0;i<pass.length();i++){
            if(!Character.isLetterOrDigit((pass.charAt(i)))){
                return false;
            }
        }
        return true;
    }

    private void onSignUp(){
        final String usernameString = userName.getText().toString().trim();
        final String emailString = email.getText().toString().trim();
        final String passwordString = password.getText().toString().trim();
        final String repasswordString = repassword.getText().toString().trim();

        /**If any of the either fields login or password are empty then the following couple actions might take place:-
         * Also if the passwords mismatch then the user will be denied a successfull registeration*/
        if(TextUtils.isEmpty(usernameString)){
            userName.setError("Please enter Username");
            userName.requestFocus();
            return;
        }
        if(TextUtils.isEmpty(emailString)){
            email.setError("Please enter Email Id");
            email.requestFocus();
            return;
        }
        if(TextUtils.isEmpty(passwordString)){
            password.setError("Please enter Password");
            password.requestFocus();
            return;
        }if(TextUtils.isEmpty(repasswordString)){
            repassword.setError("Please Re-enter Password");
            repassword.requestFocus();
            return;
        }
        if(!userNameCheck(usernameString)){
            userName.setError("Username can contain only alphabets or digits.Username cannot start with a number");
            userName.setText("");
            userName.requestFocus();
            return;
        }
        if(!checkUserNameLength(usernameString)){
            userName.setError("The username should atleast contain 8 charchacters");
            userName.setText("");
            userName.requestFocus();
            return;
        }
        if (userName.getText().toString().contains(" ")) {
            userName.setError("Spaces NOT Allowed");
            userName.requestFocus();
            return;
        }
        if(!isValidEmail(emailString)){
            email.setError("Incorrect Email format");
            email.requestFocus();
            return;
        }
        if (!repasswordString.equals(passwordString)){
            //Toast.makeText(this,"Password Mismatch.Try Again",Toast.LENGTH_SHORT).show();
            password.setGravity(10);
            password.setError("Passwords are incorrect");
            password.setText("");
            repassword.setText("");
            password.requestFocus();
            return;
        }
        if(!checkPassword(passwordString)){
            password.setError("The password should be alphanumeric and should be 8 characters long.No special symbols allowed");
            password.setText("");
            repassword.setText("");
            password.requestFocus();
            return;
        }
        if(!checkSpecial(passwordString)){
            password.setError("The password should not contain any special characters");
            password.setText("");
            repassword.setText("");
            password.requestFocus();
            return;
        }

        //If all, username,email,password and repassword have been entered then the following part takes place
        progressBar.setVisibility(View.VISIBLE);

        /*Here the user is created using a password and email and addonCompleteListener is optional part which states what to be
         done when the user has successfully logged in*/
        mAuth.createUserWithEmailAndPassword(emailString,passwordString).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                progressBar.setVisibility(View.GONE);
                if(task.isSuccessful()){
                    Toast.makeText(RegsiterPage.this,"Registered Successfully.",Toast.LENGTH_SHORT).show();
                    //To record the username in a the android application:
                    /*FirebaseUser user = mAuth.getCurrentUser();
                    if(user!=null){
                        UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
                                .setDisplayName(usernameString)
                                .build();

                        user.updateProfile(profile).addOnCompleteListener( new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if(task.isSuccessful()){
                                    Toast.makeText(RegsiterPage.this,"Awesome Profile Created",Toast.LENGTH_SHORT).show();
                                }else{
                                    Toast.makeText(RegsiterPage.this,task.getException().getMessage(),Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }*/
                    Intent intent = new Intent(getApplicationContext(),LoginPage.class);
                    startActivity(intent);
                }
                else if(task.getException() instanceof FirebaseAuthUserCollisionException) {
                    Toast.makeText(RegsiterPage.this,"You are already Registered",Toast.LENGTH_SHORT).show();
                    userName.setText("");
                    email.setText("");
                    password.setText("");
                    repassword.setText("");
                }else{
                    Toast.makeText(RegsiterPage.this,task.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    userName.setText("");
                    email.setText("");
                    password.setText("");
                    repassword.setText("");
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        if(v == signUp){
            onSignUp();
        }
    }
}

编辑: -

这是我的logcat: -

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.parma.gareebcalculator, PID: 3149
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task
com.google.android.gms.common.api.GoogleApi.zzb(com.google.android.gms.common.api.internal.zzdd)' on a null object reference
at com.google.android.gms.internal.zzdvv.zzb(Unknown Source)
at com.google.android.gms.internal.zzdwc.zza(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(Unknown
     Source)
at com.example.parma.gareebcalculator.RegsiterPage.onsignup(RegsiterPage.java:192)
at com.example.parma.gareebcalculator.RegsiterPage.onClick(RegsiterPage.java:241)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
  

找到解决方案

解决方案:如果有人来这个......就这样做......我的整个代码和一切都很完美......但是我的模拟器出了什么问题......它正在运行在API 24上...这实际上是无法追踪的,因为应用程序只兑现但从未说过如何....所以只需尝试将API更改为26(为我工作)并使用或创建新的模拟器

1 个答案:

答案 0 :(得分:0)

你的真实是空的,这就是造成这次崩溃的原因

保持检查

  if(mAuth !=null){

  }