0

I am trying to retrieve the data from my Firebase Firestore as an authenticated user (as per the defined rules) and I am also able to retrieve the same,

But when I am storing the data in a Global string then the string variable only contains it within the scope of Listener function and outside the function, it gives a NullPointerException.

For understand it, I toasted the variables inside as well as outside the function. The toast within the Listener displays the data but the toast outside the listener returns "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();
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

0 Answers0