i am getting error when trying to add phone authentication in my android app project

只愿长相守 提交于 2020-06-17 15:47:49

问题


I am trying to add phone no. authentication in my new video app( I already have Facebook and Google authentication in my app) and they are working well. I need to save and parse user data in the server and in local as well.

I do not know much about phone number authentication, please help me to fix the issue in phone no. authentication.

As I already said Facebook and google authentication working perfectly and user data from these is also saving in local and server as well.

Please make phone no. authentication work like google or Facebook.

Note - Phone no. authentication is working perfectly but the data is not storing in server and local. (phone no. authentication is storing in Firebase but not on server).

when I put phone no. it authenticates successfully but then app says "App is stopped" other than going to "main_menu".

please help me ... I am in trouble\

code of login_A where google and facebook authentication takes place, i added a button here which sends me to login_Activity where phone authentication takes place.

''' public class Login_A extends Activity {

private ImageView PhoneLogin_btn;


FirebaseAuth mAuth;
FirebaseUser firebaseUser;
IOSDialog iosDialog;

SharedPreferences sharedPreferences;

View top_view;

TextView login_title_txt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    if (Build.VERSION.SDK_INT == 26) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);
    }

    getWindow().setBackgroundDrawable(
            new ColorDrawable(android.graphics.Color.TRANSPARENT));

    this.getWindow()
            .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);



    setContentView(R.layout.activity_login);


    mAuth = FirebaseAuth.getInstance();
    firebaseUser=mAuth.getCurrentUser();

    // if the user is already login trought facebook then we will logout the user automatically
    LoginManager.getInstance().logOut();

    iosDialog = new IOSDialog.Builder(this)
            .setCancelable(false)
            .setSpinnerClockwise(false)
            .setMessageContentGravity(Gravity.END)
            .build();

    sharedPreferences=getSharedPreferences(Variables.pref_name,MODE_PRIVATE);

    findViewById(R.id.facebook_btn).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Loginwith_FB();
        }
    });



    findViewById(R.id.google_btn).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Sign_in_with_gmail();
        }
    });



    findViewById(R.id.Goback).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

     top_view=findViewById(R.id.top_view);



    login_title_txt=findViewById(R.id.login_title_txt);
    login_title_txt.setText("You need a "+getString(R.string.app_name)+"\naccount to Continue");



    SpannableString ss = new SpannableString("By signing up, you confirm that you agree to our \n Terms of Use and have read and understood \n our Privacy Policy.");
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            Open_Privacy_policy();
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ss.setSpan(clickableSpan, 99, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    TextView textView = (TextView) findViewById(R.id.login_terms_condition_txt);
    textView.setText(ss);
    textView.setClickable(true);
    textView.setMovementMethod(LinkMovementMethod.getInstance());


    printKeyHash();


    // related to phone login
    PhoneLogin_btn = (ImageView) findViewById(R.id.phone_btn);
    PhoneLogin_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openActivityPhoneLogin();
        }
    });


}

public void openActivityPhoneLogin(){
    Intent intent = new Intent(this,LoginActivity.class);
    startActivity(intent);
}


public void Open_Privacy_policy(){
    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(Variables.privacy_policy));
    startActivity(browserIntent);
}


@Override
public void onEnterAnimationComplete() {
    super.onEnterAnimationComplete();
    AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
    anim.setDuration(200);
    top_view.startAnimation(anim);
    top_view.setVisibility(View.VISIBLE);

}

@Override
public void onBackPressed() {
    top_view.setVisibility(View.GONE);
    finish();
    overridePendingTransition(R.anim.in_from_top, R.anim.out_from_bottom);

}


// Bottom two function are related to Fb implimentation
private CallbackManager mCallbackManager;
//facebook implimentation
public void Loginwith_FB(){

    LoginManager.getInstance()
            .logInWithReadPermissions(Login_A.this,
                    Arrays.asList("public_profile","email"));

    // initialze the facebook sdk and request to facebook for login
    FacebookSdk.sdkInitialize(this.getApplicationContext());
    mCallbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>()  {
        @Override
        public void onSuccess(LoginResult loginResult) {
            handleFacebookAccessToken(loginResult.getAccessToken());
            Log.d("resp_token",loginResult.getAccessToken()+"");
        }

        @Override
        public void onCancel() {
            // App code
            Toast.makeText(Login_A.this, "Login Cancel", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(FacebookException error) {
            Log.d("resp",""+error.toString());
            Toast.makeText(Login_A.this, "Login Error"+error.toString(), Toast.LENGTH_SHORT).show();
        }

    });


}

private void handleFacebookAccessToken(final AccessToken token) {
    // if user is login then this method will call and
    // facebook will return us a token which will user for get the info of user
    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    Log.d("resp_token",token.getToken()+"");
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        iosDialog.show();
                         final String id = Profile.getCurrentProfile().getId();
                        GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject user, GraphResponse graphResponse) {

                                Log.d("resp",user.toString());
                                //after get the info of user we will pass to function which will store the info in our server

                                String fname=""+user.optString("first_name");
                                String lname=""+user.optString("last_name");


                                if(fname.equals("") || fname.equals("null"))
                                    fname=getResources().getString(R.string.app_name);

                                if(lname.equals("") || lname.equals("null"))
                                    lname="";

                                Call_Api_For_Signup(""+id,fname
                                        ,lname,
                                        "https://graph.facebook.com/"+id+"/picture?width=500&width=500",
                                        "facebook");

                            }
                        });

                        // here is the request to facebook sdk for which type of info we have required
                        Bundle parameters = new Bundle();
                        parameters.putString("fields", "last_name,first_name,email");
                        request.setParameters(parameters);
                        request.executeAsync();
                    } else {

                        Toast.makeText(Login_A.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }

                }
            });
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // Pass the activity result back to the Facebook SDK
    if(requestCode==123){
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        handleSignInResult(task);
    }
    else if(mCallbackManager!=null)
        mCallbackManager.onActivityResult(requestCode, resultCode, data);

}



//google Implimentation
GoogleSignInClient mGoogleSignInClient;
public void Sign_in_with_gmail(){
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(Login_A.this);
    if (account != null) {
        String id=account.getId();
        String fname=""+account.getGivenName();
        String lname=""+account.getFamilyName();

        String pic_url;
        if(account.getPhotoUrl()!=null) {
             pic_url = account.getPhotoUrl().toString();
        }else {
            pic_url="null";
        }



        if(fname.equals("") || fname.equals("null"))
            fname=getResources().getString(R.string.app_name);

        if(lname.equals("") || lname.equals("null"))
            lname="User";
        Call_Api_For_Signup(id,fname,lname,pic_url,"gmail");


    }
    else {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, 123);
    }

}


//Relate to google login
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        if (account != null) {
            String id=account.getId();
            String fname=""+account.getGivenName();
            String lname=""+account.getFamilyName();

            // if we do not get the picture of user then we will use default profile picture

            String pic_url;
            if(account.getPhotoUrl()!=null) {
                pic_url = account.getPhotoUrl().toString();
            }else {
                pic_url="null";
            }


            if(fname.equals("") || fname.equals("null"))
                fname=getResources().getString(R.string.app_name);

            if(lname.equals("") || lname.equals("null"))
                lname="";

            Call_Api_For_Signup(id,fname,lname,pic_url,"gmail");


        }
    } catch (ApiException e) {
        Log.w("Error message", "signInResult:failed code=" + e.getStatusCode());
    }

}




// this function call an Api for Signin
public void Call_Api_For_Signup(String id,
                                String f_name,
                                String l_name,
                                String picture,
                                String singnup_type) {


    PackageInfo packageInfo = null;
    try {
        packageInfo =getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    String appversion=packageInfo.versionName;

    JSONObject parameters = new JSONObject();
    try {

        parameters.put("fb_id", id);
        parameters.put("first_name",""+f_name);
        parameters.put("last_name", ""+l_name);
        parameters.put("profile_pic",picture);
        parameters.put("gender","m");
        parameters.put("version",appversion);
        parameters.put("signup_type",singnup_type);
        parameters.put("device",Variables.device);


    } catch (JSONException e) {
        e.printStackTrace();
    }

    iosDialog.show();
    ApiRequest.Call_Api(this, Variables.SignUp, parameters, new Callback() {
        @Override
        public void Responce(String resp) {
            iosDialog.cancel();
            Parse_signup_data(resp);

        }
    });

}




// if the signup successfull then this method will call and it store the user info in local
public void Parse_signup_data(String loginData){
    try {
        JSONObject jsonObject=new JSONObject(loginData);
        String code=jsonObject.optString("code");
        if(code.equals("200")){
            JSONArray jsonArray=jsonObject.getJSONArray("msg");
            JSONObject userdata = jsonArray.getJSONObject(0);
            SharedPreferences.Editor editor=sharedPreferences.edit();
            editor.putString(Variables.u_id,userdata.optString("fb_id"));
            editor.putString(Variables.f_name,userdata.optString("first_name"));
            editor.putString(Variables.l_name,userdata.optString("last_name"));
            editor.putString(Variables.u_name,userdata.optString("first_name")+" "+userdata.optString("last_name"));
            editor.putString(Variables.gender,userdata.optString("gender"));
            editor.putString(Variables.u_pic,userdata.optString("profile_pic"));
            editor.putString(Variables.api_token,userdata.optString("tokon"));
            editor.putBoolean(Variables.islogin,true);
            editor.commit();

            Variables.sharedPreferences=getSharedPreferences(Variables.pref_name,MODE_PRIVATE);
            Variables.user_id=Variables.sharedPreferences.getString(Variables.u_id,"");

            top_view.setVisibility(View.GONE);
            finish();
            startActivity(new Intent(this, MainMenuActivity.class));



        }else {
            Toast.makeText(this, ""+jsonObject.optString("msg"), Toast.LENGTH_SHORT).show();
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

}



// this function will print the keyhash of your project
// which is very helpfull during Fb login implimentation
public void printKeyHash()  {
    try {
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName() , PackageManager.GET_SIGNATURES);
        for(Signature signature:info.signatures)
        {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.i("keyhash" , Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

} ''' below is the code of Login_A which is phone authentication]

''' public class LoginActivity extends AppCompatActivity {

private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;

private EditText mCountryCode;
private EditText mPhoneNumber;

private Button mGenerateBtn;
private ProgressBar mLoginProgress;

private TextView mLoginFeedbackText;
private EditText phoneLogin;
IOSDialog iosDialog;
SharedPreferences sharedPreferences;
View top_view;

private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;

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

    mAuth = FirebaseAuth.getInstance();
    mCurrentUser = mAuth.getCurrentUser();

    mCountryCode = findViewById(R.id.country_code_text);
    mPhoneNumber = findViewById(R.id.phone_number_text);
    mGenerateBtn = findViewById(R.id.generate_btn);
    mLoginProgress = findViewById(R.id.login_progress_bar);
    mLoginFeedbackText = findViewById(R.id.login_form_feedback);

    sharedPreferences=getSharedPreferences(Variables.pref_name,MODE_PRIVATE);


    mGenerateBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String country_code = mCountryCode.getText().toString();
            String phone_number = mPhoneNumber.getText().toString();

            String complete_phone_number = "+" + country_code + phone_number;

            if(country_code.isEmpty() || phone_number.isEmpty()){
                mLoginFeedbackText.setText("Please fill in the form to continue.");
                mLoginFeedbackText.setVisibility(View.VISIBLE);
            } else {
                mLoginProgress.setVisibility(View.VISIBLE);
                mGenerateBtn.setEnabled(false);

                PhoneAuthProvider.getInstance().verifyPhoneNumber(
                        complete_phone_number,
                        60,
                        TimeUnit.SECONDS,
                        LoginActivity.this,
                        mCallbacks
                );

            }
        }
    });

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

        @Override
        public void onVerificationFailed(FirebaseException e) {
            mLoginFeedbackText.setText("Verification Failed, please try again.");
            mLoginFeedbackText.setVisibility(View.VISIBLE);
            mLoginProgress.setVisibility(View.INVISIBLE);
            mGenerateBtn.setEnabled(true);
        }

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

            new android.os.Handler().postDelayed(
                new Runnable() {
                    public void run() {
                        Intent otpIntent = new Intent(LoginActivity.this, OtpActivity.class);
                        otpIntent.putExtra("AuthCredentials", s);
                        startActivity(otpIntent);
                    }
                },
            10000);
        }
    };


}

@Override
protected void onStart() {
    super.onStart();
    if(mCurrentUser != null){
        sendUserToHome();
    }
}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        sendUserToHome();
                        // ...
                    } else {
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid
                            mLoginFeedbackText.setVisibility(View.VISIBLE);
                            mLoginFeedbackText.setText("There was an error verifying OTP");
                        }
                    }
                    mLoginProgress.setVisibility(View.INVISIBLE);
                    mGenerateBtn.setEnabled(true);
                }
            });
}

private void sendUserToHome() {
    Intent homeIntent = new Intent(LoginActivity.this, MainMenuActivity.class);


    String id = mPhoneNumber.getText().toString();
    String fname = "" + "nishant456";
    String lname = "" + "67474";
    String pic_url = "" + "null";
    Login_A callApi = new Login_A();
    Call_Api_For_Signup(id,fname,lname,pic_url,"phone");

    homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);





    finish();
}

// this function call an Api for Signin
public void Call_Api_For_Signup(String id,
                                String f_name,
                                String l_name,
                                String picture,
                                String singnup_type) {


    PackageInfo packageInfo = null;
    try {
        packageInfo =getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    String appversion=packageInfo.versionName;

    JSONObject parameters = new JSONObject();
    try {

        parameters.put("fb_id", id);
        parameters.put("first_name",""+f_name);
        parameters.put("last_name", ""+l_name);
        parameters.put("profile_pic",picture);
        parameters.put("gender","m");
        parameters.put("version",appversion);
        parameters.put("signup_type",singnup_type);
        parameters.put("device", Variables.device);


    } catch (JSONException e) {
        e.printStackTrace();
    }

    iosDialog.show();
    ApiRequest.Call_Api(this, Variables.SignUp, parameters, new Callback() {
        @Override
        public void Responce(String resp) {
            iosDialog.cancel();
            Parse_signup_data(resp);

        }
    });

}




// if the signup successfull then this method will call and it store the user info in local
public void Parse_signup_data(String loginData){
    try {
        JSONObject jsonObject=new JSONObject(loginData);
        String code=jsonObject.optString("code");
        if(code.equals("200")){
            JSONArray jsonArray=jsonObject.getJSONArray("msg");
            JSONObject userdata = jsonArray.getJSONObject(0);
            SharedPreferences.Editor editor=sharedPreferences.edit();
            editor.putString(Variables.u_id,userdata.optString("fb_id"));
            editor.putString(Variables.f_name,userdata.optString("first_name"));
            editor.putString(Variables.l_name,userdata.optString("last_name"));
            editor.putString(Variables.u_name,userdata.optString("first_name")+" "+userdata.optString("last_name"));
            editor.putString(Variables.gender,userdata.optString("gender"));
            editor.putString(Variables.u_pic,userdata.optString("profile_pic"));
            editor.putString(Variables.api_token,userdata.optString("tokon"));
            editor.putBoolean(Variables.islogin,true);
            editor.apply();

            Variables.sharedPreferences=getSharedPreferences(Variables.pref_name,MODE_PRIVATE);
            Variables.user_id=Variables.sharedPreferences.getString(Variables.u_id,"");

            top_view.setVisibility(View.GONE);
            finish();
            startActivity(new Intent(this, MainMenuActivity.class));



        }else {
            Toast.makeText(this, ""+jsonObject.optString("msg"), Toast.LENGTH_SHORT).show();
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

}

} '''

please help me......


回答1:


You have not given any id to the top_view. You are using top_view before starting MainMenuActivity in the LoginActivity class. This might me one of the reason for the app to stop.



来源:https://stackoverflow.com/questions/62323174/i-am-getting-error-when-trying-to-add-phone-authentication-in-my-android-app-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!