如果相关数据位于单独的节点上,如何从 Firebase 过滤 Listview 上的数据?

问题描述 投票:0回答:1

我有同一应用程序的两个版本,一个管理员版本和一个客户端版本。

客户端版本可以报告以下紧急类型:

医疗援助、警察援助和消防援助

虽然管理版本的凭据上有部门:

警察、医院、消防局

我希望我的管理版本上的列表视图仅显示以下内容:

为管理员用户提供警察援助,为管理员用户提供医院医疗援助,等等...

这是我的数据库布局(我选择“警察”作为测试部门):

{
  "Admin Users": {
    "vnpLogkr7pYndxx40XJB5PVulea2": {
      "Department": {
        "Fire Dept": 0,
        "Hospital": 0,
        "Police": 1
      },
      "Name": "Rafael Aurelius"
    }
  },

"Users": {
    "W5RZg4leD0XR6ZWCNClr9Dt99XG3": {
      "Scenario": "Scenario 2",
      "emergencyType": "Police Assistance",
      "userTimestamp": 1712208811229
    }
  }

我已经为每个部门设置了值,如果选择则为 1,如果未选择则为 0,因为我计划将过滤基于我之前实现的用户访问阻止系统,但到目前为止我还没有成功进行过滤.

这是没有过滤的列表视图:

package com.example.rescuealertadmin;

import static android.content.ContentValues.TAG;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.firebase.ui.database.FirebaseListAdapter;
import com.firebase.ui.database.FirebaseListOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

public class LocationLog extends AppCompatActivity {
    FirebaseListAdapter<MainData> locationAdapter;
    ListView locationList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_locationlog);

        this.locationList = findViewById(R.id.locationView);

        
        Query filteredQuery = FirebaseDatabase.getInstance().getReference().child("Users");

        FirebaseListOptions<MainData> options = new FirebaseListOptions.Builder<MainData>()
                .setLayout(R.layout.location_item)
                .setQuery(filteredQuery, MainData.class)
                .build();

        locationList.setAdapter(locationAdapter);
        locationAdapter = new FirebaseListAdapter<MainData>(options) {
            @Override
            protected void populateView(@NonNull View v, @NonNull MainData model, int position) {
                TextView emergencyTypeView = v.findViewById(R.id.emergencyText);
                TextView scenarioView = v.findViewById(R.id.ScenarioText);
                Button emergencyButton = v.findViewById(R.id.itemButton);
                emergencyTypeView.setText(model.getEmergencyType());
                scenarioView.setText(model.getScenario());
                String selectedUid = locationAdapter.getRef(position).getKey();

                emergencyButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Get the location data of the selected user
                        assert selectedUid != null;
                        DatabaseReference selectedUserLocationRef = FirebaseDatabase.getInstance()
                                .getReference().child("User Location").child(selectedUid);

                        selectedUserLocationRef.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot locationSnapshot) {
                                if (locationSnapshot.exists()) {
                                    Double latitude = locationSnapshot.child("latitude").getValue(Double.class);
                                    Double longitude = locationSnapshot.child("longitude").getValue(Double.class);

                                    if (latitude != null && longitude != null) {
                                        // Data retrieved successfully, now start the new activity
                                        Intent intent = new Intent(LocationLog.this, EmergencyDetails.class);
                                        intent.putExtra("Emergency Type", model.getEmergencyType());
                                        intent.putExtra("Scenario", model.getScenario());
                                        intent.putExtra("Latitude", latitude);
                                        intent.putExtra("Longitude", longitude);
                                        startActivity(intent);
                                    } else {
                                        // Handle missing location data
                                        Log.e(TAG, "Latitude or Longitude is null");
                                    }
                                } else {
                                    // Handle if the location data for the selected user doesn't exist
                                    Log.e(TAG, "Location data does not exist for UID: " + selectedUid);
                                }
                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError locationError) {
                                // Handle location data retrieval error
                                Log.e(TAG, "Location data retrieval error: " + locationError.getMessage());
                            }
                        });
                    }
                });

                Log.d(TAG, "Emergency Type: " + model.getEmergencyType());
            }
        };


    }

    @Override
    protected void onStart() {
        super.onStart();
        if (locationAdapter != null) {
            locationAdapter.startListening();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (locationAdapter != null) {
            locationAdapter.stopListening();
        }
    }
}

在列表视图上成功过滤这些数据的方法有哪些?

java android firebase firebase-realtime-database
1个回答
0
投票

根据评论中的答案,请使用以下代码行:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference uidRef = db.child("Admin Users").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            DataSnapshot policeSnapshot = snapshot.child("Department").child("Police");
            if (policeSnapshot.exists()) {
                DatabaseReference usersRef = db.child("Users");
                Query queryByDepartment = usersRef.orderByChild("emergencyType").equalTo("Police" + " Assistance");
                queryByDepartment.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DataSnapshot> task) {
                        if (task.isSuccessful()) {
                            DataSnapshot usersSnapshot = task.getResult();
                            for (DataSnapshot userSnapshot : usersSnapshot.getChildren()) {
                                String scenario = userSnapshot.child("Scenario").getValue(String.class);
                                Log.d("TAG", scenario);
                            }
                        } else {
                            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
                        }
                    }
                });

            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

此代码读取经过身份验证的管理员的节点,然后检查

Police
部门节点是否存在,如果存在,则在
users
节点内执行查询,以获取设置了
emergencyType
字段的所有用户到“警察协助”,最后打印 logcat 中
Scenario
字段的值。根据您的数据库架构,logcat 中的结果将是:

Scenario 2
© www.soinside.com 2019 - 2024. All rights reserved.