Skip to content Skip to sidebar Skip to footer

Why Is The Array List Ratingitemlist Showing As Empty After Insertion Of Several Items?

While its in the Document Snapshot loop its adding the ratings to the ratingItemList. I know this for sure because I'm also printing the size of the list in the Log and it's increa

Solution 1:

if you call for background thread result in first line and print it on very next line, your callback method does not give guarantee to run before the very next line. It will start to execute thread of first line and without waiting for response run the next line. So you are getting it empty.

Check list size also in callback onSuccess() method, after for loop:

publicclassYourRatingextendsAppCompatActivity {
private List<ratingItem> ratingItemList;
private FirebaseFirestore db;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_your_rating);

    ratingItemList = newArrayList<>();


    db = FirebaseFirestore.getInstance();
    db.collection("userRatings").get().addOnSuccessListener(newOnSuccessListener<QuerySnapshot>() {
        @OverridepublicvoidonSuccess(QuerySnapshot queryDocumentSnapshots) {
            if (!queryDocumentSnapshots.isEmpty()) {
                Log.d("Check1", "Ratings Exist");
                List<DocumentSnapshot> documentSnapshots = queryDocumentSnapshots.getDocuments();
                for (DocumentSnapshot doc : documentSnapshots) {
                    Stringrating= doc.getString("Rating");
                    //Log.d("Rating",rating);
                    com.google.firebase.Timestampdate= doc.getTimestamp("Date");
                    //Log.d("Date",date.toString());ratingItemnewRatingItem=newratingItem(rating, date);
                    Log.d("Rating", newRatingItem.getRating());
                    Log.d("Date", newRatingItem.getTimestamp().toString());


                    ratingItemList.add(newRatingItem);
                    Log.d("Size ", String.valueOf(ratingItemList.size()));

                }
                if (ratingItemList.isEmpty()) {
                    Log.d("Empty", "Empty List");
                }
                for (ratingItem r : ratingItemList) {
                    Log.d("Rating1", r.getRating());
                    Log.d("Date1", r.getTimestamp().toString());
                }
            } else {
                Toast.makeText(YourRating.this, "No ratings available!", Toast.LENGTH_LONG).show();
            }
        }
    });

}

}

Solution 2:

you success listener runs on the background thread and it is a promise that will be run when the data will be obtained from the firebase. on the other hand the piece of code where you check the array list is empty or not runs on the ui thread. It does not wait for the data to be fetched.

Post a Comment for "Why Is The Array List Ratingitemlist Showing As Empty After Insertion Of Several Items?"