When I System.out.println(this.notes)
in constructor, it works successfully. But in the getNotes() function, it gives null. Notes.java class:
package com.akcware.agendanote;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.Timestamp;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
class Notes {
private FirebaseUser user;
private ArrayList<Note> notes = new ArrayList<>();
Notes(FirebaseUser user) {
this.user = user;
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Notes").whereEqualTo("uid", this.user.getUid()).get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (int i = 0; i < queryDocumentSnapshots.getDocuments().size(); i++) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots
.getDocuments().get(i);
String uid = documentSnapshot.getString("uid");
String note = documentSnapshot.getString("note");
Timestamp time = documentSnapshot.getTimestamp("time");
String image = documentSnapshot.getString("image");
Note noteobj = new Note(uid, note, time, image);
System.out.println(noteobj);
Notes.this.notes.add(noteobj);
System.out.println(Notes.this.notes);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
System.err.println("ERROR: " + e.getLocalizedMessage());
e.printStackTrace();
}
});
}
FirebaseUser getUser() {
return this.user;
}
ArrayList<Note> getNotes() {
System.out.println("Get: " + this.notes);
return this.notes;
}
}
In main activity (onCreate function):
FirebaseAuth mAuth;
FirebaseUser mUser;
Notes notes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
ArrayList<Note> notes_arr;
notes = new Notes(mUser);
notes_arr = notes.getNotes();
System.out.println("Not2: " + notes_arr);
Output:
I/System.out: Get: []
Not2: []
I/System.out: com.akcware.agendanote.Note@a47c2b0
[com.akcware.agendanote.Note@a47c2b0]
Such as you see, In main class and in getNotes() function that in Notes.java, are returning null or [], but in constructor it returns class correctly.