0

I've made this function to check a number of error in a field of my app. So I've made this code:

private int getSegnalations(final Location location, DatabaseReference ref, final HashMap<Location,String>mapLocation) {
     final List<Segnalation> matches = new LinkedList<>();
     final String key = mapLocation.get(location);
     Query query = ref.child("segnalation");

     segnalationDialog = createProgressDialog(getActivity(),segnalationDialog,getString(R.string.download));
     query.addValueEventListener(new ValueEventListener()
     {
         @Override
         public void onDataChange(DataSnapshot dataSnapshot)
         {

          stopProgressDialog(segnalationDialog);

          for(DataSnapshot dS : dataSnapshot.getChildren())
          {
            Segnalation segnalation = dS.getValue(Segnalation.class);

            Log.d("keys:",segnalation.getIdPark()+","+mapLocation.get(location));

            if(segnalation.getIdPark().equals(key))
            {
              matches.add(segnalation);
            }
          }
         }

         @Override
         public void onCancelled(DatabaseError databaseError)
         {
          stopProgressDialog(segnalationDialog);
             showErrorMessage(getActivity(),getString(R.string.dbProblem));
         }
     });

     return matches.size();
 }

the bug is that Log.d show me this lines:

D/keys:: -KTijPwCAd7M7wdZms3S,-KTy7n4WcCx3IUWRsRDX
D/keys:: -KTjJYQGW8_k6Dpi_z7W,-KTy7n4WcCx3IUWRsRDX
D/keys:: -KTjKby31PU7PkJWrb5U,-KTy7n4WcCx3IUWRsRDX
D/keys:: -KTy7n4WcCx3IUWRsRDX,-KTy7n4WcCx3IUWRsRDX

but if is bypass and returns me size 0 and not 1.

Why? What is the error in this code?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
nani
  • 382
  • 5
  • 15
  • Firebase data is loaded asynchronously. That means by the time you return `matches.size()` nothing has been loaded from the server yet. The solution is to move the code that needs the size into the `onDataChange()`. See http://stackoverflow.com/questions/31700830/synchronous-blocking-operation/31702957 – Frank van Puffelen Oct 13 '16 at 14:48
  • @FrankvanPuffelen sorry, I have to do two different queries to two child, how to get data to all? – nani Oct 13 '16 at 16:12

1 Answers1

1

The problem with you code is due to synchronization. While query.addValueEventListener() starts a new Thread to execute its operation. Your background Thread countinues its execution and ends the method with return matches.size(); which is offcourse 0 because this list is being populated in other thread which executes long after your getSegnalations() method is over.

M.Waqas Pervez
  • 2,492
  • 2
  • 19
  • 33
  • getSegnalations() is execute in an onDataChange( ) of another query..it seems this the problem? How could I fix it? – nani Oct 13 '16 at 14:28
  • finally it works, I have put all in onDataChange()..thank you! – nani Oct 14 '16 at 08:42