0

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.

  • 2
    Thats because firebase is asynchronous inside the succeslistener you will have get the noets, try calling getNotes inside that method and you will see the correct result – Marcos Vasconcelos Mar 01 '20 at 18:59
  • @MarcosVasconcelos I copied the code to getNotes() function. And then returned it. But it returned [] again. What can I do that? In flutter there're futures but I think in java there're not. – Aşkın Kadir Çekim Mar 01 '20 at 19:05
  • 1
    And code that needs the data from Firestore need to be inside `onSuccess` or be called from there. See https://stackoverflow.com/questions/51000169/how-to-check-a-certain-data-already-exists-in-firestore-or-not/51002413#51002413 If you've done that, but can't get it to work, update your question to include the [minimal code that shows that problem](http://stackoverflow.com/help/mcve). – Frank van Puffelen Mar 01 '20 at 19:24
  • @FrankvanPuffelen I know it should be called from onSuccess. But I use it with main class so I should return data with a function to manage in main class. How can I do that? – Aşkın Kadir Çekim Mar 01 '20 at 20:16
  • 1
    You can't **return** data from an asynchronous callback. The closest you can get is call back into that main class. The question I linked shows exactly how to do that with a custom interface (`AlreadyBookedCallback` there, but it can be anything you need for your use-case). – Frank van Puffelen Mar 01 '20 at 21:26
  • @AşkınKadirÇekim As Frank van Puffelen mentioned in his comment, you can't return data from an asynchronous callback. Please check the duplicate to see why do you have this behavior and how can you solve this using a custom callback. – Alex Mamo Mar 02 '20 at 10:01

0 Answers0