1

Here I compare x and y variables with my Firebase database. If i find the right result I want to return the key.

private String checkParkeer() {
    final Integer parkX = 4;
    final Integer parkY = 1;
    final String[] result = new String[1];

    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    final DatabaseReference ref = database.getReference("parkeerpaal");

    ref.addValueEventListener(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot){

            for (DataSnapshot snapshot : dataSnapshot.getChildren()){

                Log.d("test", snapshot.getKey());

                Integer newX = Integer.parseInt(snapshot.child("x").getValue().toString());
                Integer newY = Integer.parseInt(snapshot.child("y").getValue().toString());

                if (newX <= parkX+2 && newX >= parkX-2) {
                    if (newY <= parkY + 2 && newY >= parkY - 2) {
                        result[0] = snapshot.getKey();
                    }
                }
                break;
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    Log.d("result", result[0]);
    return result[0];
}

Now the Log.d("test", snapshot.getKey()); logs "P1" (this is the result I need)

But when I put it in result, Log.d("result", result[0]);or return result[0];give errors.

This is my first time doing this stuff. how do I resolve this? what am I doing wrong?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
user3322672
  • 153
  • 2
  • 13

1 Answers1

1

You cannot simply return that value outside onDataChange() method because this method has an asynchronous behaviour, which means that this method is called even before you are trying to get the data from the database. A quick fix in your case would be to use that value only inside onDataChange() method or a better solution, would be to use the last part of my answer from this post in which using your own callback, you can achieve using that value also outside onDataChange() method.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193