-2

I am making a project in which when a sensor is tripped it sends the data to the Firebase realtime database and then to be outputted in an Android application. Firebase creates a unique key for the data once it enters the database so I am unsure how to retrieve the data.

Database screenshot

error that appears when app crashes

I have tried some code to output the data but it just crashes the App. The app opens onto the page that is trying to display the data.

DatabaseReference databaseReference =

FirebaseDatabase.getInstance().getReference();

    Query lastQuery = databaseReference.child("sensor").orderByKey().limitToLast(1);
    lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String message = dataSnapshot.child("Detection").getValue().toString();
            sensorValue.setText(message);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            //Handle possible errors.
        }
    });
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

0

Whe you query the database to get the value of your Detection property, you need to loop throught the DataSnapshot object using getChildren() method like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query lastQuery = rootRef.child("sensor").orderByKey().limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String detection = ds.child("Detection").getValue(String.class);
            Log.d(TAG, detection);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
lastQuery.addListenerForSingleValueEvent(valueEventListener);

I quote: "When you execute a query against the Firebase database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result."

The result in your logcat will be:

2019-04-22 13:58:58
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193