无法从Firestore数据库中获取数据

时间:2020-01-21 18:12:58

标签: android google-cloud-firestore

我尝试了以下代码从我的Firestore数据库中获取代码。数据库结构如下所示: Database Structure 设备集合中的所有文档都需要获取并显示在应用程序上。 但是for循环上方的toast起作用了,一旦代码进入for循环就不起作用了,因此for循环内的toast不能正常工作,因此无法获取数据。 我尝试了所有可用于获取数据的方法,但没有一个起作用。请提供解决方案。 预先感谢。

public class CurrentStatusDevicesFragment extends Fragment {

    private static final String name = "title";
    private static final String type = "description";
    private TextView textViewData;
    private  String houseId;
    private String userId;
    private String data;
    FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
    FirebaseAuth firebaseAuth=FirebaseAuth.getInstance();
    //DocumentReference dRef = firebaseFirestore.collection("Houses/").document(houseId);


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.device_profile, container, false);
        textViewData = (TextView) rootView.findViewById(R.id.textViewData);

        userId = firebaseAuth.getCurrentUser().getUid();
        firebaseFirestore.collection("Users")
                .document("userId").get()
                .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(Task<DocumentSnapshot> task) {
                        if (task.isSuccessful()) {
                            DocumentSnapshot document = task.getResult();
                            if (document.exists()) {
                                houseId = document.getString("HOUSE_ID");
                            } else {
                                Log.d("TAG", "No such document");
                            }
                        } else {
                            Log.d("TAG", "get failed with ", task.getException());
                        }
                    }
                });

        CollectionReference cRef = firebaseFirestore.collection("Devices");
        cRef.whereEqualTo("HOUSE_ID", houseId).addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
                if(e!=null){
                    Log.w("TAG","Listen Failed",e);
                    return;
                }
                data="";
                Toast.makeText(getContext(),"Hello",Toast.LENGTH_SHORT).show();
                for(QueryDocumentSnapshot document:queryDocumentSnapshots){
                    Toast.makeText(getContext(),"Bye",Toast.LENGTH_SHORT).show();
                    Device device = document.toObject(Device.class);
                    String name = device.getName();
                    String type = device.getType();
                    data+= "Name: "+name+"\nType of device: "+type;
                }
                textViewData.setText(data);
            }
        });
 });
        return rootView;
    }



//Device Class
package com.example.android.aide;

public class Device {
    private String NAME;
    private String TYPE;
    private String documentId;

    public Device(){}

    public String getDocumentId(){
        return documentId;
    }

    public void setDocumentId(String documentId){
        this.documentId = documentId;
    }

    public Device(String NAME, String TYPE){
        this.NAME = NAME;
        this.TYPE = TYPE;
    }

    public String getName() {
        return NAME;
    }

    public String getType() {
        return TYPE;
    }
}

device_profile.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textViewData"
        android:layout_width="match_parent"
        android:textSize="30sp"
        android:layout_height="wrap_content" />

</LinearLayout>

`

1 个答案:

答案 0 :(得分:1)

您正在使用异步检索的值添加侦听器。知道您具有该值之后,您应该添加该侦听器。

firebaseFirestore.collection("Users")
    .document("userId").get()
    .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    houseId = document.getString("HOUSE_ID");

                    // Now you can use the value of houseId
                    listenForHouseId();

                } else {
                    Log.d("TAG", "No such document");
                }
            } else {
                Log.d("TAG", "get failed with ", task.getException());
            }
        }
        });

将您的Snapshot侦听器移至某个函数:

public void listenForHouseId(){
    CollectionReference cRef = firebaseFirestore.collection("Devices");
    cRef.whereEqualTo("HOUSE_ID", houseId).addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
            if(e!=null){
                Log.w("TAG","Listen Failed",e);
                return;
            }
            data="";
            Toast.makeText(getContext(),"Hello",Toast.LENGTH_SHORT).show();
            for(QueryDocumentSnapshot document:queryDocumentSnapshots){
                Toast.makeText(getContext(),"Bye",Toast.LENGTH_SHORT).show();
                Device device = document.toObject(Device.class);
                String name = device.getName();
                String type = device.getType();
                data+= "Name: "+name+"\nType of device: "+type;
            }
            textViewData.setText(data);
        }
    });
}