1

I am calling a function which further fetches data from firebase DB.

Starting call:

List<DataObj> dataObjList = FireBaseHandler.getInstance().getDataFromServer(context, _id);

getDataFromServer():

{
.
.
.
localDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot dataItemSnapshot: dataSnapshot.getChildren()) {
                    DataItem dataItem = dataItemSnapshot.getValue(DataItem.class);
                    if (dataItem != null && dataItem.get_id() != -1) {
                        dataItemList.add(dataItem);
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        return dataItemList;
}

But before I get data from Firebase, this function returns a list of empty objects. How to handle this case?

Pranjal Kaler
  • 483
  • 3
  • 14
  • listOfEmptyObjects or an emptyList ? – Kashish Sharma May 17 '20 at 07:05
  • Its an empty list but I want to avoid that. It takes a while before list is populated, but return statement out of this addListenerStatement, gets called before list is populated – Pranjal Kaler May 17 '20 at 07:07
  • Then just check if the list is empty return else do your stuff. – Kashish Sharma May 17 '20 at 07:09
  • There is nothing else to do. This function call is to fetch data from FirebaseDB. – Pranjal Kaler May 17 '20 at 07:11
  • In onData change, check if dataSnapshot.getChildren() is empty then return else start your for loop. – Kashish Sharma May 17 '20 at 07:13
  • Such dummy loops is not a good approach in programming – Pranjal Kaler May 17 '20 at 07:31
  • The results you're expecting will be returned in a callback (as the request is on bg thread) so it's very obvious that your code will return the empty list first and then the actual result. I still don't get it what you want to achieve but few solutions, either let it return an emptyList and in callback call notifyItemRangeInserted(..,..) if using a RecyclerView or if you want the result list only, don't return anything from function and call whatever you want to do in the success callback itself. – Kashish Sharma May 17 '20 at 10:04

0 Answers0