Firebase用户ID在同一活动中的特定时间获取空引用

时间:2019-04-11 10:28:31

标签: android firebase firebase-authentication

我正在活动中,用户可以从firebase输入OTP。如果自动验证(通过播放服务)不起作用,则用户必须在那时输入我的代码,而我的代码却无法获得uid null,而是在自动验证发生时(onVerificationCompleted,)用户ID正在为空 还是我不知道这是检查用户是否正确的地方。请帮助我,因为该项目对我很重要

   PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    @Override
    public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {

        Toast.makeText(getApplicationContext(), "verification completed",
                Toast.LENGTH_LONG).show();

        check();


        SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
        editor.putString("text", "signed in");
        editor.apply();



       // Intent myIntent = new Intent(VerifyPhoneActivity.this, 
    MainActivity.class);
       // startActivity(myIntent);




    }

这是我完整的验证活动代码

    package com.example.EduMangalore;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.concurrent.TimeUnit;

public class VerifyPhoneActivity extends AppCompatActivity {

//These are the objects needed
//It is the verification id that will be sent to the user
private String mVerificationId;
DatabaseReference mDatabase;

//The edittext to input the code
private EditText editTextCode;
final String MY_PREFS_NAME = "MyPrefsFile";

private FirebaseAuth mAuth;
String code;
String mobile;
String codesent;
public FirebaseAuth.AuthStateListener authListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_verify_phone);

    mAuth = FirebaseAuth.getInstance();
    mDatabase = FirebaseDatabase.getInstance().getReference();
    sendVerificationCode();


    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {


            verifySignInCode();


        }
    });


  }


private void verifySignInCode() {

    final EditText fd = (EditText) findViewById(R.id.et1);
    String value = fd.getText().toString();


    final EditText sd = (EditText) findViewById(R.id.et2);
    String value1 = sd.getText().toString();
    // int finalValue1=Integer.parseInt(value1);


    EditText td = (EditText) findViewById(R.id.et3);
    String value2 = td.getText().toString();


    EditText fod = (EditText) findViewById(R.id.et4);
    String value3 = fod.getText().toString();


    EditText fid = (EditText) findViewById(R.id.et5);
    String value4 = fid.getText().toString();


    EditText sid = (EditText) findViewById(R.id.et6);
    String value5 = sid.getText().toString();


    code = value + value1 + value2 + value3 + value4 + value5;


    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codesent, code);

    signInWithPhoneAuthCredential(credential);


   }


 private void check()
 {



    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    FirebaseUser userid = FirebaseAuth.getInstance().getCurrentUser();

    final String uid = userid.getUid();
    ref.child("Users");
    ref.child(mobile).child(uid);


    Log.d("myTag", mobile);
    Log.d("myTag", uid);


      DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("Users");

       userRef.orderByChild("mobile").equalTo(mobile).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {


            if (dataSnapshot.getValue() != null) {



                Toast.makeText(getApplicationContext(), "Welcome Back",
                        Toast.LENGTH_LONG).show();

                SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
                editor.putString("text", "signed in");
                editor.apply();

                Intent myIntent = new Intent(VerifyPhoneActivity.this, MainActivity.class);
                startActivity(myIntent);




            } else {


                Intent intent = new Intent(VerifyPhoneActivity.this, Signup.class);

                intent.putExtra("mobile", mobile);

                startActivity(intent);


            }


        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });


  }



    private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {


                    if (task.isSuccessful()) {



                       check();


                    } else {

                        Toast.makeText(getApplicationContext(), "login faild",
                                Toast.LENGTH_LONG).show();


                        // Sign in failed, display a message and update the UI
                        // Log.w(TAG, "signInWithCredential:failure", task.getException());
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid

                            Toast.makeText(getApplicationContext(), "Please enter the correct OTP",
                                    Toast.LENGTH_LONG).show();

                        }
                    }
                }
            });
}





    PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    @Override
    public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {

        Toast.makeText(getApplicationContext(), "verification completed",
                Toast.LENGTH_LONG).show();

        check();


        SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
        editor.putString("text", "signed in");
        editor.apply();



       // Intent myIntent = new Intent(VerifyPhoneActivity.this, MainActivity.class);
       // startActivity(myIntent);




    }





    @Override
    public void onVerificationFailed(FirebaseException e) {

        Toast.makeText(getApplicationContext(), "sending faild" + e,
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
        // super.onCodeSent(s, forceResendingToken);


        Toast.makeText(getApplicationContext(), "sent",
                Toast.LENGTH_LONG).show();
        codesent = s;

    }
};

private void sendVerificationCode() {


    Intent intent = getIntent();
    mobile = intent.getStringExtra("mobile");


    Toast.makeText(getApplicationContext(), mobile,
            Toast.LENGTH_LONG).show();
    String phonenumber = "+91" + mobile;


    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phonenumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            mCallbacks);        // OnVerificationStateChangedCallbacks

 }


}

0 个答案:

没有答案