您好,我是Android開發新手。我目前正在嘗試使用Google的Firebase作爲其後端系統來構建基本的Android應用程序。將Facebook用戶存儲在Firebase中
我有一個「用Facebook登錄」按鈕,無論何時點擊此按鈕,它都會打開一個對話框,用戶輸入他的Facebook憑據以訪問應用程序。完成後,如果是第一次登錄,我想將他的電子郵件,姓名和ID存儲在Firebase中,如果這不是他第一次登錄,我想更新他的信息。
我做了一個名爲User(POJO)的類,我將用它來表示這些數據。我的問題是我似乎不知道在哪裏放置存儲此信息的代碼。 這裏是我的MainActivity類別:
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();
}
}
});
}
}
這裏是我的用戶等級:
public class User {
private String id;
private String name;
private String email;
public User(){
}
public User(String id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
謝謝您的時間
它看起來像你已經把代碼放在你的AuthStateChanged監聽器上。這不適合你嗎? –
@RosárioPereiraFernandes否,這個解決方案中不是 – hallaksec