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

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

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

这是我的代码:

@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:字符串密码,扇区已在onViewCreated外部声明

java android google-cloud-firestore textview
1个回答
0
投票

OnCompleteListener异步完成,因此您需要将setTexts放置在其onComplete方法内。换句话说,在访问扇区和pincode局部变量以进行串联以形成sectorText和pincodeText字符串时,它们不会填充数据。

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

}
© www.soinside.com 2019 - 2024. All rights reserved.