-2

I've ran into a wall and cannot find a way around it. I have the following class, where I get information from a Firestore db inside the fetchToDo() method.

public class FetchToDo {
private static final String LOG_TAG = FetchToDo.class.getName();

public static final String AUTHOR_KEY = "author";
public static final String EMAIL_KEY = "e-mail";

/**
 * Access cloud Firestore instance
 */
FirebaseFirestore db = FirebaseFirestore.getInstance();

private String mTitle;
private String mDescription;

private DocumentReference mDocRef;

public void fetchToDo() {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    final String emailOfUser = user.getEmail();

    mDocRef = FirebaseFirestore.getInstance().document("users/" + emailOfUser);

    mDocRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            if (documentSnapshot.exists()) {
                Log.i(LOG_TAG, "Method ran");
                mTitle = documentSnapshot.getString(EMAIL_KEY);
                mDescription = documentSnapshot.getString(AUTHOR_KEY);

            }
        }
    });
}

public String getTitle(){
    fetchToDo();
    return this.mTitle;
}

Once I have that information, I want to store it into a RecyclerView and display it. I do the following when I create the RecyclerView.

public void createRecyclerView(){
    //Get a reference of the RecyclerView
    mToDoList = (RecyclerView) findViewById(R.id.rv_to_do);

    //Assign a Layout manager - this case a linear one
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    mToDoList.setLayoutManager(layoutManager);

    mToDoList.setHasFixedSize(true);

    //Create a new ToDoAdapter

    FetchToDo fetchToDo = new FetchToDo();
    String title = fetchToDo.getTitle();
    String[] fua = {"Test1", title};
    mAdapter = new ToDoAdapter(fua);
    mToDoList.setAdapter(mAdapter);
}

The issue is that the RecyclerView is showing two boxes, one with the "Test1" String and one that is empty.

Thank you.

Bandes
  • 23
  • 5
  • Put log lines in your code to see the order that things are called. You'll find that Firebase APIs are asynchronous, and you'll need to deal with them that way. https://medium.com/google-developers/why-are-the-firebase-apis-asynchronous-e037a6654a93 – Doug Stevenson Mar 14 '18 at 00:17

1 Answers1

0

You have to think of FetchToDo() as an async function. And what you are doing is is asking for the "title" before it has actually been fetched.

My suggestion would be to return it in the FetchToDo() function or any sort of completion listener. Or, you could make the mTitle variable static and create a simple observable to load the RecyclerView when title is updated.

Drei
  • 669
  • 1
  • 6
  • 22