Data coming from Firebase takes time to finish loading and disrupts the ordering of objects

2

I'm trying to sort an object by a value that comes from Firebase. I use a JsonParcer class to list the database and according to the ID get the field I need in Firebase, which in the case is a coordinate so that with it I calculate the distance. The order will be made by this field.

1. I call JsonParcer on AnsycTask doInBackground.

2. In the onPostExecute I call the Collection.Sort (data).

3. Then I add it to the Adapter for RecyclerView.

PROBLEM: Some objects do not end up being loaded in the Firebase Query and when they arrive in the OnPostExecute they have nulls or Zero values, hindering the ordering.

I NEED: That ordering is only done when all objects are populated with Firebase values, so that soon afterwards I play on my adapter.

I'll play the classes below and an example of how the data comes:

public class MototaxiJSONParcer {

    static LatLng currentLocationLatLong;

    public static List<TaxiMototaxiEtc> parseDados(String content, final LatLng coordenadaUsu) {


        try {
            JSONArray jsonArray = new JSONArray(content);
            final List<TaxiMototaxiEtc> dadosList = new ArrayList<>();

            for (int i = 0; i< jsonArray.length(); i++) {

                final JSONObject jsonObject = jsonArray.getJSONObject(i);
                final TaxiMototaxiEtc dados = new TaxiMototaxiEtc();


                // Pegar ID, ir no DateTime e buscar Coordenada ------------------------------------
                DatabaseReference raiz = FirebaseDatabase.getInstance().getReference();
                Query consultaRealTime;
                consultaRealTime = raiz.child("location/" + jsonObject.getString("id")).limitToLast(1);
                final int finalI = i;
                consultaRealTime.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        LocationData localizacao = new LocationData();
                        for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
                            localizacao = childSnapshot.getValue(LocationData.class);
                        }

                        currentLocationLatLong = new LatLng(localizacao.latitude, localizacao.longitude);

                        if (currentLocationLatLong != null) {
                            int distancia = (int) SphericalUtil.computeDistanceBetween(currentLocationLatLong, coordenadaUsu);

                            dados.setDistancia(distancia);

                        }

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Log.i("Local", "The read failed: " + databaseError.getCode());
                    }
                });

                dados.setName(jsonObject.getString("name"));
                dadosList.add(dados);


            } // end For


            return dadosList;

        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

}

INTERACTION: Check below the data interaction and check that some Firebase data arrives only later, which hinders the perfect ordering that I execute inside DoInBackGround:

DENTRO DO PARCER: Teones - 3491
DENTRO DO PARCER: Gabriel - 2663
DENTRO DO PARCER: Alisson - 3564
----------------------------------------------------------------
SEM ORDENAR: Teones - 3491
SEM ORDENAR: Gabriel - 2663
SEM ORDENAR: Alisson - 3564
SEM ORDENAR: Carlos Augusto - 0
SEM ORDENAR: Tiago Fontes - 0
SEM ORDENAR: Jaciene - 0
-----------------------------------------------------------------
ORDENADO: Carlos Augusto - 0
ORDENADO: Tiago Fontes - 0
ORDENADO: Jaciene - 0
ORDENADO: Gabriel - 2663
ORDENADO: Teones - 3491
ORDENADO: Alisson - 3564

DENTRO DO PARCER: Carlos Augusto - 1918
DENTRO DO PARCER: Tiago Fontes - 4042
DENTRO DO PARCER: Jaciene - 4337802
    
asked by anonymous 26.12.2018 / 00:32

1 answer

0

I'm not sure what to do with Firebase, but I'm not sure what to do with it. UI, but it seems to me that your MototaxiJSONParcer class is already called in doInBackground, so you can try like this:

AtomicBoolean consultaCompleta = new AtomicBoolean(false);
consultaRealTime.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        LocationData localizacao = new LocationData();
        for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
            localizacao = childSnapshot.getValue(LocationData.class);
        }

        currentLocationLatLong = new LatLng(localizacao.latitude, localizacao.longitude);

        if (currentLocationLatLong != null) {
            int distancia = (int) SphericalUtil.computeDistanceBetween(currentLocationLatLong, coordenadaUsu);
            dados.setDistancia(distancia);
        }
        dados.setName(jsonObject.getString("name"));

        consultaCompleta.set(true);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        consultaCompleta.set(true);
        Log.i("Local", "The read failed: " + databaseError.getCode());
    }
});

while (true) {
    // TODO: isso pode demorar a vida toda, considere adicionar um timeout
    if (consultaCompleta.get()) {
        dadosList.add(dados);
        break;
    }
}
    
08.01.2019 / 15:59