-1

I'm creating an app with a Facebook login mechanisme.
I'm trying to determine whether this is the first time this user have logged in to the app (thus firebase has added it to the Authentication section)
I'm trying to fetch the data with the current user id, and if the value for it is null to add it to the database.
The thing is that the datarequest is async, thus i don't know how to continue.
Tried using this post but with no success

This is my code (I'm trying to query the database in 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

Edit:
The question is not whether one can wait until the data is fetched, but how can I test this is the first time the user logged in

DsCpp
  • 2,259
  • 3
  • 18
  • 46
  • You can also take a look **[here](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method/47853774)**. – Alex Mamo Mar 23 '18 at 11:00

1 Answers1

0

Firebase APIs are all asynchronous. This is by design. It's important that you deal with them asynchronously. If you attempt to make the main thread of your app block on some Firebase API, your app will be difficult to use, and possibly crash with an ANR.

Please read more about why Firebase APIs are asynchronous in this article.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • I've posted this thread in my question. I understand the API, but i'm sure i'm not the first one with this problem. do you have any idea on how to test whether this is the first time the user have logged in to the database? – DsCpp Mar 22 '18 at 17:01
  • If you want to store information about the user, use the database for that. You will have to do your work with the asynchronous APIs. – Doug Stevenson Mar 22 '18 at 17:17
  • I'm sorry, but i think i have failed to explain that the Firebase API is no the issue here. I'm trying to resolve the question wether this is the first time the user have logged in to the application, something i'm sure a lot of people have queried before me. I'm here to listen to people with more experience than me, and not to have a war of the minds with some of them. – DsCpp Mar 22 '18 at 17:35
  • Then perhaps you could ask another question that describes what you're trying to accomplish. As it stands now, the question looks like it's hung up on trying to use Firebase APIs synchronously, which you can't do. https://stackoverflow.com/help/how-to-ask – Doug Stevenson Mar 22 '18 at 18:27