Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Android addListenerForSingleValueEvent sometimes not returning data

When my application starts, I check the current user's details in my Firebase database (I'm storing it's uid for that).

I'm attaching addListenerForSingleValueEvent to user's ref to read it's data.

My problem is that sometimes, it doesn't return any value, neither success nor failure.

Only clearing application's data solves it, but of course forces the user to login again.

I've read some posts at SO, but didn't find any solution.

Here's my piece of code:

DatabaseReference newUser =    
FirebaseDatabase.getInstance().getReference("users/"+uid);
newUser.addListenerForSingleValueEvent(new ValueEventListener()     
    @Override
    public void onDataChange(DataSnapshot snapshot) {}

    @Override
    public void onCancelled(DatabaseError databaseError) {}
});
like image 500
Adi Avatar asked Jun 08 '16 12:06

Adi


2 Answers

Please try like this. If you can't solver by this, send share me source code for this part. ...

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {

    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()){
            final HashMap<String, Object> dataMap = (HashMap<String, Object>) dataSnapshot.getValue();
            for (String key : dataMap.keySet()){
                Object data = dataMap.get(key);
                try{
                    HashMap<String, Object> moneyData = (HashMap<String, Object>) data;
                    Money money = new Money(("", "");
                }catch (ClassCastException cce){
                    try{
                        name = String.valueOf(dataMap.get("username"));
                        email = String.valueOf(dataMap.get("useremail"));
                    }catch (ClassCastException cce2){
                    }
                }
            }                            
        // do something
        }else {
        // when empty data
        }
    }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    }
});
like image 124
Miah G. Avatar answered Sep 21 '22 14:09

Miah G.


The recommendation I've seen for this is to call keepSynced(true) on the Query object.

like image 39
John O'Reilly Avatar answered Sep 17 '22 14:09

John O'Reilly