Home > Net >  android callback with firestore not working
android callback with firestore not working

Time:04-19

i'm trying to get data from firestore and i want to get data before executing the rest of the code so i used callbacks at first i created a class DbManger with a static methode and an interface

public class DbManager
{

    private static FirebaseFirestore db;
    private static FirebaseAuth auth;
    private static FirebaseUser currentUser;



    public static void getField(String uid,String key, FirebaseCallBack callBack) {
        db= FirebaseFirestore.getInstance();
        auth=FirebaseAuth.getInstance();
        currentUser = auth.getCurrentUser();

        db.collection(Keys.USERS_KEY).document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot documentSnapshot = task.getResult();
                String field = documentSnapshot.getString(key);
                callBack.onCallBack(field);
                }
            }
        });
    }

    public interface FirebaseCallBack
    {
         void onCallBack(String field) ;
    }

}

in the other activity i tried to get data with the help of the DbManager class like that

if(currentUser!=null){
        DbManager.getField(currentUser.getUid(), Keys.ACCOUNT_TYPE_KEY, new DbManager.FirebaseCallBack() {
            @Override
            public void onCallBack(String field) {
                accountType=field;
            }
        });
        
    }
if(accountType.equals(Keys.ADMIN_ACCOUNT_TYPE_KEY))
        selectFragment(new HomeFragment());
    else
        selectFragment(new ModulesFragment());

but i didn't get any data

CodePudding user response:

The problem is that your if(accountType.equals(Keys.ADMIN_ACCOUNT_TYPE_KEY)) runs before accountType=field. The easiest way to see this is by adding some logging, or setting breakpoints on those line and running in the debugger.

The solution for this is always the same: the code that needs the data, needs to be in the callback that is invoked once the data is available. So the simplest fix for you is:

if(currentUser!=null){
    DbManager.getField(currentUser.getUid(), Keys.ACCOUNT_TYPE_KEY, new DbManager.FirebaseCallBack() {
        @Override
        public void onCallBack(String field) {
            accountType=field;
            if(accountType.equals(Keys.ADMIN_ACCOUNT_TYPE_KEY))
                selectFragment(new HomeFragment());
            else
                selectFragment(new ModulesFragment());
        }
    });
}

Also see:

  • Related