从Firebase ID向共享首选项保存价值的问题

时间:2017-03-08 17:39:53

标签: android firebase sharedpreferences firebase-authentication

我在后端数据库中使用firebase ID作为我的用户ID。在我的开场活动中,我检查了一个firebase ID,然后将其保存到共享首选项。只有使用firebase ID才能继续。

问题是,现在我正在进入下一个屏幕,并且firebase ID未保存到共享首选项。我使用以下firebase库:

compile 'com.google.firebase:firebase-core:9.2.1'
compile 'com.google.firebase:firebase-auth:9.2.1'

以下是我在onCreate方法中使用的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    cp = AmazonS3.getProvider(context);
    FacebookSdk.sdkInitialize(context);
    quizImage.clear();
    intent = new Intent(this, MainActivity.class);
    res = getResources();
    setContentView(R.layout.loadingscreen);


    firebaseAuth = FirebaseAuth.getInstance();



    sp = PreferenceManager.getDefaultSharedPreferences(context);
    spEditor = sp.edit();

    cognitioID = sp.getString("Cognito","");
    firebaseID = sp.getString("Firebase", "");
   // String userID = sp.getString("USERID", "");
    Log.i(LOG_TAG, "firebaseID: " + firebaseID);

    if (cognitioID == "") {
        new cognitoID().execute();
    }
    shouldGoToMainActivity = false;
    numberOfDownloadedFiles = 0;



     if(sp.getString("Firebase","").isEmpty()) {
        Log.i(LOG_TAG, "splash activity no firebase ID");

        configureGoogleSignIn();

        LoginButton fbLogin = (LoginButton) findViewById(R.id.fb_login_button);
        fbLogin.setVisibility(View.VISIBLE);


        //Login with Facebook and volley write to users.php
        callbackManager = CallbackManager.Factory.create();
        fbLogin.setReadPermissions(Arrays.asList("user_friends", "email", "user_location"));

        fbLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.i(LOG_TAG,"Facebook Login Success");
                fbAccessToken = loginResult.getAccessToken();

//Make the Call to below method to get and set firebase ID

                firebaseAuthWithFacebook(fbAccessToken);

                final GraphRequest request = GraphRequest.newMeRequest(
                        fbAccessToken, new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.d(LOG_TAG,"Facebook graph reqest "+ response + "");
                                fbUser = object;


                                try {
                                    fullName = object.getString("name");
                                    firstName = object.getString("first_name");
                                    lastName = object.getString("last_name");
                                    email = object.getString("email");
                                    ageRange = object.getString("age_range");
                                    gender = object.getString("gender");
                                    userid = firebaseID;
                                    Utils.getZipCodeForCurrentLocation(context)
                                            .observeOn(Schedulers.io())
                                            .subscribe(new Action1<String>() {
                                                @Override
                                                public void call(String s) {
                                                    zip = s;
                                                    Log.i(LOG_TAG, "Zip code in Facebook: " + s);

                                                }
                                            });

                                    Log.i(LOG_TAG, "name from fb graph/age "+ fullName +" "+ ageRange);
                                    Log.i("fb id", userid);
                                    spEditor.putString("firstName", firstName);
                                    spEditor.putString("lastName", lastName);
                                    spEditor.putString("fullName", fullName);
                                    spEditor.putString("email", email);
                                    spEditor.putString("Firebase", userid);
                                    spEditor.putString("zip", zip);

                                    spEditor.commit();

                                    uploadUserInfo();

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

                        });

                Bundle fbparameters = new Bundle();
                fbparameters.putString("fields", "name, email, age_range, gender, first_name, last_name ");
                request.setParameters(fbparameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException error) {
                Snackbar snackbar = Snackbar
                        .make(findViewById(android.R.id.content), "Facebook SignIn Error, please try again", Snackbar.LENGTH_SHORT);

                snackbar.show();
                Log.d("facebook Login", "facebook error - " + error);
            }

        });

    }

    else {
        Log.i(LOG_TAG, firebaseID + " is assigned and written");
        shouldGoToMainActivity = true;
    }


     firebaseListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
            if (firebaseUser != null){
                //Authenticated with Firebase
                firebaseID = firebaseUser.getUid();
                spEditor.putString("Firebase", userid);
                spEditor.commit();
                Log.i("Splash Firebase", "onAuthStateChanged: signed_in:  " + firebaseUser.getUid());
            } else{
                Log.i("Splash Firebase", "onAuthStateChanged: signed_out");
            }
        }
    };

    firebaseAuth.addAuthStateListener(firebaseListener);

    //end of OnCreate
    }



     @Override
public void onStart(){
    super.onStart();
    firebaseAuth.addAuthStateListener(firebaseListener);
}

@Override
public void onStop(){
    super.onStop();
    if (firebaseAuth != null){
        firebaseAuth.removeAuthStateListener(firebaseListener);
    }
}


 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==RC_RESOLVE_ERROR){

        intentInProgress = false;
        if (resultCode != RESULT_OK) {
            isSignedIn = false;
            //Maybe show a dialog to user ?
            return;
        }
        //Attemp connection again.
        if (googleApiClient.isConnecting()) {
            googleApiClient.connect();
        }
    }
    else if (requestCode == RC_SIGN_IN) {
        hideProgressDialog();
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(intent);
        handleGoogleSignInResult(result);
    }
    startActivity(intent);
    finish();
}


  /**
 * setup Google Api client and signInButton
 */
private void configureGoogleSignIn(){
    googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    googleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addOnConnectionFailedListener(this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
            .addApi(Plus.API)
            .addConnectionCallbacks(this)
            .build();

    SignInButton gLogin = (SignInButton) findViewById(R.id.g_login_button);
    gLogin.setSize(SignInButton.SIZE_STANDARD);
    gLogin.setScopes(new Scope[]{Plus.SCOPE_PLUS_LOGIN});
    //  gLogin.setOnClickListener(this);

    gLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            signInByGPlus();
        }
    });
    gLogin.setVisibility(View.VISIBLE);
}


private void signInByGPlus(){
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
    startActivityForResult(signInIntent, GPLUS_SIGN_IN);
}

/**
 * Save userId and user's full name if login successful. If not, main screen will be
 * started anyway (as a guest)
 * @param result
 */
private void handleGoogleSignInResult(GoogleSignInResult result){
    if (null == result){
        Log.w(LOG_TAG, "login result is null (user canceled login - proceed as a guest)");
        return;
    }
    Log.d(LOG_TAG, "handleGoogleSignInResult (is successful?): " + result.isSuccess());
    if (!result.getStatus().isSuccess()){
        isSignedIn = false;
        intentInProgress = false;
        GoogleSignInAccount googleAccount = result.getSignInAccount();
        firebaseAuthWithGoogle(googleAccount);
        if(result.getStatus().hasResolution()||result.getStatus().getStatusCode() == CommonStatusCodes.SIGN_IN_REQUIRED){
            freshSignIn();


        }

    }
    else {
        intentInProgress = false;
        isSignedIn = true;
        acct = result.getSignInAccount();

    }



    fullName = acct.getDisplayName();
    email = acct.getEmail();
    userid = firebaseID;
    /** google+ return fullname in format first name " " last name */
    String[] nameParts = fullName.split(" ");
    if (nameParts.length == 2){
        firstName = nameParts[0];
        lastName = nameParts[1];
    }else {
        firstName = "";
        lastName = "";
    }
    /** Google has no idea about gender */
    gender = "";

    Log.i(LOG_TAG, "full name: " + fullName);
    Log.i(LOG_TAG, "first name: " + firstName);
    Log.i(LOG_TAG, "last name: " + lastName);
    Log.i(LOG_TAG, "email: " + email);
    Log.i(LOG_TAG, "id: " + userid);

    spEditor.putString("firstName", firstName);
    spEditor.putString("lastName", lastName);
    spEditor.putString("fullName", fullName);
    spEditor.putString("Firebase", firebaseID);

    spEditor.putString("email", email);

    Utils.getZipCodeForCurrentLocation(this)
            .observeOn(Schedulers.io())
            .subscribe(new Action1<String>() {
                @Override
                public void call(String s) {
                    zip = s;
                    Log.i(LOG_TAG, "Zip code: " + s);
                    spEditor.putString("zip", s);
                    uploadUserInfo();
                }
            });
    spEditor.commit();
}


private void firebaseAuthWithGoogle(GoogleSignInAccount acct){
    Log.d("SplashActivity firebase", "firebaseAuthWtihGoogle: "+ acct.getId());
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    firebaseID = user.getUid();
    spEditor.putString("Firebase", firebaseID);
    spEditor.commit();


    AuthCredential firebaseCredential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    firebaseAuth.signInWithCredential(firebaseCredential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("SpalshActivity firebase", "signInwithCredential: onComplete:" + task.isSuccessful());

                        if(!task.isSuccessful()){
                            Log.w("SplashActivity firebase", task.getException());
                            Toast.makeText(SplashActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    shouldGoToMainActivity = true;
}

private void firebaseAuthWithFacebook(AccessToken token){
    Log.d("SPlash Firebase Face", "firebaseAuthWithFacebook:" + token);
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    firebaseID = user.getUid();
    spEditor.putString("Firebase", firebaseID);
    spEditor.commit();


    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    firebaseAuth.signInWithCredential(credential)
               .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                   @Override
                   public void onComplete(@NonNull Task<AuthResult> task) {
                       Log.d("Splash Firebase Face", "signInWithCredential[FB]:onComplete: " + task.isSuccessful());

                       if(!task.isSuccessful()){
                           Log.w("Splash Firebase Face", "signInWithCredential[FB]" + task.getException());
                           Toast.makeText(SplashActivity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
                       }
                   }
               });

    shouldGoToMainActivity = true;
}

0 个答案:

没有答案