TextView 无法使用来自 Firestore 的数据设置文本

TextView not able to setText with data from Firestore

我正在从 Firestore 获取数据。我想将字符串数据设置为 TextView。我能够成功获取数据。即我可以将其记录在 logcat 中。但是当我尝试设置文本时,它显示 null 代替数据

这是我的代码:

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        yourSector=view.findViewById(R.id.Sector_tv);
        yourPincode=view.findViewById(R.id.Pincode_tv);

        DocumentReference docRef = db.collection("customerUsers").document(userID);
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        pincode = document.getString("pincode");
                        sector = document.getString("sector");
                        Log.d("pincodetest", "onComplete: "+pincode);

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

        String sectorText="Sector : " + sector;
        String pincodeText="Pincode : "+pincode;
        yourSector.setText(sectorText);
        yourPincode.setText(pincodeText);

我的logcat(显示正确的数据):

2020-06-14 00:41:43.779 14633-14633/? D/pincodetest: onComplete: 110001

当我设置文本时,我的屏幕上出现: 扇区:空

PS: 字符串 pincode,sector 已经在 onViewCreated

之外声明

OnCompleteListener 异步完成,因此您需要将 setTexts 放在它的 onComplete 方法中。换句话说,当访问扇区和密码局部变量以进行串联以形成扇区文本和密码文本字符串时,扇区和密码局部变量不会填充数据。

简单来说,onComplete 方法在 字符串连接后运行。因此,在字符串连接过程中,变量 sector 和 pincode 的值仍然为空。

我对下面的代码做了一点修正:

if (document.exists()) {
    pincode = document.getString("pincode");
    sector = document.getString("sector");
    Log.d("pincodetest", "onComplete: "+pincode);

    String sectorText="Sector : " + sector;
    String pincodeText="Pincode : "+pincode;
    yourSector.setText(sectorText);
    yourPincode.setText(pincodeText);

}