简体   繁体   English

未从 firestore 数据库中获取数据

[英]Data not being fetched from firestore database

I have tried the below code to fetch code from my firestore database.The database structure is as shown: Database Structure All the documents from Devices collection needs to be fetched and displayed on application.我已尝试使用以下代码从我的 firestore 数据库中获取代码。数据库结构如下所示:数据库结构设备集合中的所有文档都需要获取并显示在应用程序上。 But the toast above for loop is working and as soon as the code goes inside for loop it does not work.So the toast inside for loop not working and hence data is not being fetched.但是 for 循环上面的 toast 正在工作,一旦代码进入 for 循环,它就不起作用。所以 for 循环内的 toast 不起作用,因此没有获取数据。 I tried all the methods we can use to fetch data,none of them working.Please provide me the solution.我尝试了所有我们可以用来获取数据的方法,但都没有用。请提供解决方案。 Thanks in advance.提前致谢。

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

<?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>

` `

You're adding a listener using a value that is retrieved asynchronously.您正在使用异步检索的值添加侦听器。 You should add the listener after you know you have the value.你应该在你知道你有价值之后添加监听器。

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());
            }
        }
        });

Move your Snapshot listener to a function:将您的快照侦听器移动到一个函数:

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);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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