Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/178.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在Firebase中存储Facebook用户_Android_Facebook_Firebase_Firebase Realtime Database_Firebase Authentication - Fatal编程技术网

Android 在Firebase中存储Facebook用户

Android 在Firebase中存储Facebook用户,android,facebook,firebase,firebase-realtime-database,firebase-authentication,Android,Facebook,Firebase,Firebase Realtime Database,Firebase Authentication,你好,我是Android开发的新手。我目前正试图用谷歌的Firebase作为其后端系统构建一个基本的android应用程序 我有一个“使用Facebook登录”按钮,每当点击该按钮时,就会打开一个对话框,用户在其中输入他的Facebook凭据以访问该应用程序。完成后,如果是他第一次登录,我想将他的电子邮件、姓名和id存储在Firebase中,如果不是他第一次登录,我想更新他的信息 我创建了一个名为User(POJO)的类,我将使用它来表示这些数据。我的问题是,我似乎不知道把存储这些信息的代码放在

你好,我是Android开发的新手。我目前正试图用谷歌的Firebase作为其后端系统构建一个基本的android应用程序

我有一个“使用Facebook登录”按钮,每当点击该按钮时,就会打开一个对话框,用户在其中输入他的Facebook凭据以访问该应用程序。完成后,如果是他第一次登录,我想将他的电子邮件、姓名和id存储在Firebase中,如果不是他第一次登录,我想更新他的信息

我创建了一个名为User(POJO)的类,我将使用它来表示这些数据。我的问题是,我似乎不知道把存储这些信息的代码放在哪里。 这是我的主要活动课:

public class MainActivity extends AppCompatActivity {

    //Declare our view variables
    private LoginButton mLoginButton;
    private CallbackManager mCallbackManager;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private FirebaseDatabase mDatabase;
    private DatabaseReference mDatabaseReference;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);

        //Initialize callback manager
        mCallbackManager = CallbackManager.Factory.create();

        //Assign the views to the corresponding variables
        mLoginButton = (LoginButton) findViewById(R.id.login_button);

        //Assign the button permissions
        mLoginButton.setReadPermissions("email", "public_profile");

        //Create instance of database
        mDatabase = FirebaseDatabase.getInstance();
        mDatabaseReference = mDatabase.getReference();

        //Assign the button a task
        mLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.d(TAG, "facebook:onSuccess:" + loginResult);
                handleFacebookAccessToken(loginResult.getAccessToken());
            }

            @Override
            public void onCancel() {
                Log.d(TAG, "facebook:onCancel");
            }

            @Override
            public void onError(FacebookException error) {
                Log.d(TAG, "facebook:onError", error);
            }
        });

        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                //Get currently logged in user
                FirebaseUser user = firebaseAuth.getCurrentUser();

                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());

                    // Name, email address
                    String name = user.getDisplayName();
                    String email = user.getEmail();

                    // The user's ID, unique to the Firebase project. Do NOT use this value to
                    // authenticate with your backend server, if you have one. Use
                    // FirebaseUser.getToken() instead.
                    String uid = user.getUid();

                    //Create user
                    final User loggedIn = new User(uid, name, email);

                    mDatabaseReference.child("users").child(loggedIn.getId()).setValue(loggedIn);

                    mDatabaseReference.child("users").addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // This method is called once with the initial value and again
                            // whenever data at this location is updated.

                        }

                        @Override
                        public void onCancelled(DatabaseError error) {
                            // Failed to read value
                            Log.w(TAG, "Failed to read value.", error.toException());
                        }
                    });

                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                }
            }
        };
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Pass the activity result back to the Facebook SDK
        mCallbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

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

    //If user successfully signs in the LoginButton's onSuccess callback method
    // get an access token for the signed-in user, exchange it for a Firebase credential
    // and authenticate with Firebase using the Firebase credential

    private void handleFacebookAccessToken(AccessToken token) {
        Log.d(TAG, "handleFacebookAccessToken:" + token);

        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.

                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInWithCredential", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}

感谢您的时间

您已经完成了大部分工作,因此我将创建两种方法供您使用

protected void getUserInfo(final LoginResult login_result){

    GraphRequest data_request = GraphRequest.newMeRequest(
            login_result.getAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(
                        JSONObject object,
                        GraphResponse response) {
                    try {
                        String facebook_id = object.getString("id");
                        String f_name = object.getString("name");
                        String email_id = object.getString("email");
                        String token = login_result.getAccessToken().getToken();
                        String picUrl = "https://graph.facebook.com/me/picture?type=normal&method=GET&access_token="+ token;

saveFacebookCredentialsInFirebase(login_result.getAccessToken());

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
    Bundle permission_param = new Bundle();
    permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
    data_request.setParameters(permission_param);
    data_request.executeAsync();
    data_request.executeAsync();
}
这是您在firebase中保存数据的地方

private void saveFacebookCredentialsInFirebase(AccessToken accessToken){
  AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(!task.isSuccessful()){
                Toast.makeText(getApplicationContext(),"Error logging in", Toast.LENGTH_LONG).show();
            }else{
               Toast.makeText(getApplicationContext(),"Login in Successful", Toast.LENGTH_LONG).show();  
            }
        }
    });    
}
private void saveFacebookCredentialsInFirebase(AccessToken AccessToken){
AuthCredential credential=FacebookAuthProvider.getCredential(accessToken.getToken());
firebaseAuth.signInWithCredential(凭证).addOnCompleteListener(这是新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
如果(!task.issusccessful()){
Toast.makeText(getApplicationContext(),“登录时出错”,Toast.LENGTH_LONG.show();
}否则{
Toast.makeText(getApplicationContext(),“登录成功”,Toast.LENGTH_LONG.show();
}
}
});    
}

我将firebase降级为9.6.0以避免Google Play服务错误,并在用户使用handleFacebookAccessToken方法中的凭据登录后保存了该用户。

看起来您已经将代码放在了AuthStateChanged侦听器上。这对你不起作用吗?@RosárioPereiraFernandes不,它不在这个解决方案中,我如何返回我在函数
getUserInfo
中收集的用户信息?在return语句之后调用
onCompleted
,由于该语句,我将获得空数据
private void saveFacebookCredentialsInFirebase(AccessToken accessToken){
  AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(!task.isSuccessful()){
                Toast.makeText(getApplicationContext(),"Error logging in", Toast.LENGTH_LONG).show();
            }else{
               Toast.makeText(getApplicationContext(),"Login in Successful", Toast.LENGTH_LONG).show();  
            }
        }
    });    
}