无法评估FirebaseFirestore的DocumentReference的OnCompleteListener之外的全局String变量

时间:2018-08-09 05:44:11

标签: java android firebase google-cloud-firestore

我正在尝试以经过身份验证的用户身份(根据定义的规则)从Firebase Firestore检索数据,并且我也能够检索相同的数据,

但是,当我将数据存储在Global字符串中时,字符串变量仅将其包含在Listener函数的范围内,并且在函数之外,因此会给出 NullPointerException

为了理解它,我在函数内部和外部都敬酒了。侦听器内的祝酒显示数据,但侦听器外的祝酒返回"null null"

  

Announcement.java

public class Announcement extends AppCompatActivity {

FirebaseFirestore db;
String header[],body[];
ArrayList<String> data;
Map<String, Object> data2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_announcement);
    db = FirebaseFirestore.getInstance();

    header=new String[4];
    body=new String[4];


    DocumentReference docRef = db.collection("Announcements").document("1");
    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    Log.d("", "DocumentSnapshot data: " + document.getData());
                    header[1] = document.getString("Header1");
                    header[2] = document.getString("Header2");
                    header[3] = document.getString("Header3");
                    body[1] = document.getString("Body1");
                    body[2] = document.getString("Body2");
                    body[3] = document.getString("Body3");
                    Toast.makeText(Announcement.this, header[1]+" "+body[1], Toast.LENGTH_LONG).show();
                } else {
                    Log.d("", "No such document");
                }
            } else {
                Log.d("", "get failed with ", task.getException());
            }
        }
    });

     Toast.makeText(this, header[1]+" "+body[1], Toast.LENGTH_LONG).show();
}

0 个答案:

没有答案