我正在使用Facebook登录机制创建应用程序
我试图确定这是否是该用户第一次登录应用程序(因此firebase已将其添加到“身份验证”部分)
我尝试使用当前用户ID获取数据,如果它的值为null,则将其添加到数据库中。
问题是数据请求是异步的,因此我不会这样做。我知道如何继续。
使用this post尝试但没有成功
这是我的代码(我试图在testRegisterNewUser()中查询数据库)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_customer);
mLoginButton = (LoginButton) findViewById(R.id.login_button);
mLoginButton.setVisibility(View.GONE);
mCallbackManager = CallbackManager.Factory.create();
mLoginButton.setReadPermissions("email", "public_profile");
mLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAccessToken(loginResult.getAccessToken());
Toast.makeText(MainCustomerActivity.this, "Login Success", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancel() {
Toast.makeText(MainCustomerActivity.this, "Cancelled", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(FacebookException error) {
Log.d(TAG, error.toString());
Toast.makeText(MainCustomerActivity.this, "Error!", Toast.LENGTH_SHORT).show();
}
});
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) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
currentUser = mAuth.getCurrentUser();
testRegisterNewUser();
updateUI();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(MainCustomerActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
//TODO: HANDLE BAD LOGIN
}
// ...
}
});
}
private void testRegisterNewUser() {
String uid = currentUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(uid);
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
testRegisterUserName = (String) dataSnapshot.getValue();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//this is where I want to find whether this uid is already in the database
if(testRegisterUserName != null){
return;
}
else{
//this is where I want to store to the database
编辑:
问题不在于是否可以等到获取数据,但我如何测试这是用户第一次登录
答案 0 :(得分:0)
Firebase API都是异步的。这是设计的。异步处理它们非常重要。如果您尝试在某个Firebase API上创建应用程序块的主线程,则您的应用程序将难以使用,并且可能会因ANR而崩溃。
请在this article中详细了解Firebase API的异步原因。