0

The question may sound weird. I have the following custom Object that I named ItemUser:

private UserInfo user_info;
private List<UserAchievement> user_achievements;

Both fields have getters and setters. My Firestore's database looks like this:

enter image description here

I would like to get the List size instead of re-calling the database and getting the size of the collection from a separated call that would consume much resources and take a lot of time (3-4s).

Firstly I'm getting the data using this:

mDB.collection("COLLECTION_NAME").document("USER_ID").get()

Inside the onCompletedListener I'm getting the custom object as the following:

ItemUser mUser = task.getResult().toObject(ItemUser.class);

Now, when I'm trying to get the size of the user_achievements, a NullPointerException popups saying I can't get the size of a null reference.

Therefore the user_achievements is null. I think the way I'm defining user_achievements in my custom Object is the reason for this exception.

The question is: How could this be possible done without recalling the database to count only the size?

I have the main custom Object ItemUser and its children are 'healthy' except user_achievements because of the way it's defined - List<UserAchievement>.

So, any suggestions to overpass this issue?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Jaeger
  • 1,646
  • 8
  • 27
  • 59

1 Answers1

1

How could this be possible done without recalling the database to count only the size?

No, because Cloud Firestore is a real-time database and items can be added or deleted, so to get the size of a list you need to query the database and use a get() call.

If you want to count the number of documents beneath a collection (which can be added to a list), please see my answer from this post in which I have explained that task.getResult().size() can help you solve the problem.

Edit:

mDB.collection("COLLECTION_NAME").document("USER_ID").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            int size = task.getResult().size();
            Log.d(TAG, String.valueOf(size));
        }
    }
});
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • I should state that I'm using `get()` on a document, which means I'll have `OnCompleteListener` rather than `QuerySnapshot`. Therefore `size()` isn't available as a method. – Jaeger Jul 11 '18 at 19:11
  • Why are you using `OnCompleteListener` and not `OnCompleteListener`? – Alex Mamo Jul 12 '18 at 08:11
  • Because I'm listening on the document in the first example `mDB.collection("COLLECTION_NAME").document("USER_ID").get()`. Using `QuerySnapshot` shows a `Couldn't resolve` error for mistype of the parameter. – Jaeger Jul 12 '18 at 22:54
  • You shoul use the code as in my updated answer. Don't also forget to add the corresponding dependencies. – Alex Mamo Jul 13 '18 at 10:53