Data uploads into the wrong node. What's wrong in the code?

时间:2017-08-05 11:17:26

标签: java android firebase firebase-realtime-database

I have to upload the current location of the driver to the busid("1" or "2") node which has the logged in driver's Uid. But, the problem is that it always uploads the location to node "1" even if the Uid is present under node "2". I need help in finding which node (either "1" or "2") has the Uid as the child.

int totalbusno = 2;
String driverbusid = "1";
mDatabaseReference  = FirebaseDatabase.getInstance().getReference();
busReference = mDatabaseReference.child("Busno");
lat = location.getLatitude();
lon = location.getLongitude();
mUser = FirebaseAuth.getInstance().getCurrentUser();
assert mUser != null;
userid = mUser.getUid();



busReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(int i = 1; i <= totalbusno; i++){
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                if(ds.child(String.valueOf(i)).hasChild(userid)){
                    driverbusid = String.valueOf(i);
                    break;
                }
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Submitdriverlocation submitdriverlocation = new Submitdriverlocation(lat, lon);
mDatabaseReference.child("Busno").child(driverbusid).child(userid).child("location").setValue(submitdriverlocation).addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if(task.isSuccessful()){
            Toast.makeText(DriverMapsActivity.this, "Location Updated", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(DriverMapsActivity.this, "Update Failed", Toast.LENGTH_SHORT).show();
        }
    }
});

Database Structure

1 个答案:

答案 0 :(得分:0)

You have constant value of driver id, check on top of your code its String driverbusid = "1";

That's why your data is always pushing on node with key 1.

// This will always refer to node with key 1
mDatabaseReference.child("Busno").child(driverbusid) 

And update your for loop.

   for(int i = 1; i < totalbusno + 1; i++) 

Your for loop should execute for next value which 2.