简体   繁体   中英

How to fetch the data from different node from Firebase realtime database?

I am new to Java and Firebase Realtime Database. Currently, I'm doing a project where the user can track the host location when the user inserts a tracking ID. Hence, I need to fetch the data of the host location when the user inserts the correct id. Now I facing the problem of the program searching the database when the user inserted the tracking ID.

Here is my database result. 这是我的数据库。

Below are the way how I fetch my data to the program.

 private void isTrackingID() { String userTrackingID = enterTracking.getText().toString().trim(); //Long userTrackingIDNumber = Long.parseLong(userTrackingID); Toast.makeText(this, "Tracking ID = " + userTrackingID, Toast.LENGTH_SHORT).show(); DatabaseReference reference = FirebaseDatabase.getInstance().getReference("HostID"); Query query = reference.orderByChild("TrackingID/id").equalTo(userTrackingID); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { Log.i("checking", "this is value message"); enterTracking.setError(null); //String IDfromDatabase = dataSnapshot.child(userTrackingID).getValue(String.class); for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) { latitudefromDatabase = String.valueOf(dataSnapshot1.child("HostLocation").child("latitude").getValue()); Log.i("testing for latitude", latitudefromDatabase); longitudefromDatabase = String.valueOf(dataSnapshot1.child("HostLocation").child("longitude").getValue()); Log.i("testing for longitude", longitudefromDatabase); Intent intent = new Intent(getApplicationContext(), MapsActivity.class); intent.putExtra("latitude", latitudefromDatabase); intent.putExtra("longitude", longitudefromDatabase); startActivity(intent); } }else { enterTracking.setError("Invalid Tracking ID from database"); enterTracking.requestFocus(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.d("error", databaseError.getMessage()); } }); }

The program should get the host location when the user inserted the tracking ID. However, I keep receiving "Invalid Tracking ID from the database." when inserted the correct tracking id. So guys, where and how should I do the correction? Thank you very much.

The problem in your code lies in the following line of code:

Query query = reference.orderByChild("TrackingID/id").equalTo(userTrackingID);

Firebase Realtime Database queries can only return objects elements one level deeper in the tree. There is no way you can query such a database schema using a simple query. Besides that, there is a level (the UID perhaps) missing from your reference. So to be able to get all the tracking of all users where the "id" property holds that value of "444xxx", you might consider adding a new node in your database structure like so:

Firebase-root
  |
  --- tracking
        |
        --- id: "444xx"
        |
        --- uid: "loiJ ... OD53"
        |
        --- latitude: 1.858625
        |
        --- longitude: 103.0855767

In this way, you be able to get those elements using the following query:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference trackingRef = rootRef.child("tracking");
Query query = trackingRef.orderByChild("id").equalTo(444xxx);

As you can see, if you need the user details, the UID is also present. The above practice is called denormalization and is a common practice when it comes to Firebase. For a better understanding, I recommend you see this video, Denormalization is normal with the Firebase Database .

Also, when you are duplicating data, there is one thing that needs to keep in mind. In the same way, you are adding data, you need to maintain it. In other words, if you want to update/delete an item, you need to do it in every place that it exists.

in your database node, you have Tracking and in query, you have added TrackingID so just use Traking/id instead of TrakingID/id check the code below.

Query query = reference.orderByChild("TrackingID/id").equalTo(userTrackingID);



Query query = reference.orderByChild("Tracking/id").equalTo(userTrackingID);

You can look at my code:

            DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
            reference.child("Users").orderByChild("phone").equalTo(number)
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            if (snapshot.getChildrenCount() > 0) {
                                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                                    if (dataSnapshot.getChildrenCount() > 0) {
                                        UserData userData = dataSnapshot.getValue(UserData.class);
                                        Intent intent = new Intent(container.getContext(), UserDetailActivity.class);
                                        intent.putExtra("userData", userData);
                                        startActivity(intent);
                                    }
                                }
                            }else{
                                Toast.makeText(container.getContext(), "This mobile is not exist", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {

                        }
                    });

这是我的数据库结构。我也在获取两个级别

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM