-1

I'm using in my Android project Firebase Firestore and in one of my activities I have to get the data and save it in a List in order to calculate a few things. The problem is that, wherever I put the code to fetch the data, this action is always the last one (looking in the Logcat). Therefore, my List is always empty when I try to calculate. How can I manage to retrieve the data first and then continue with the process? Does anyone know why it is always the last process done?

Sorry, there're a few words in Portuguese, but nothing really important

    private List<Painel> paineis = new ArrayList<>();
    private List<Inversor> inversores = new ArrayList<>();

    FirebaseFirestore paineisBD = FirebaseFirestore.getInstance();
    FirebaseFirestore inversoresBD = FirebaseFirestore.getInstance();

@Override
    public void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);

        LoadData();

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dim_resultado_card_fragment, container, false);


        Calculate();


        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true); //para o tamanho do recycleview não mudar

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                Adapter_Produtos adapter = (Adapter_Produtos) recyclerView.getAdapter();

                if (produtosList.size() == linearLayoutManager.findLastCompletelyVisibleItemPosition() + 1) {
                    //List<Produtos_Class> listAux = ((MainActivity) getActivity().getSetCarList(10));
                    List<Produtos_Class> listAux = new ArrayList<>();
                    for (int i = 0; i < listAux.size(); i++) {
                        adapter.addListItem(listAux.get(i), produtosList.size());
                    }
                }
            }
        });


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); //Deixar scroolView padrão
        recyclerView.setLayoutManager(linearLayoutManager);

        adapter = new Adapter_Produtos(produtosList);
        adapter.setRecyclerViewOnClick(this);
        Collections.sort(produtosList, Produtos_Class.menor_valor);
        recyclerView.setAdapter(adapter);

        return view;
    }

    private void LoadData() {

        paineisBD.collection("paineis").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        Log.d("PAINEIS", "ID: " + document.getId() + " => " + document.getData());
                        paineis.add(new Painel((document.getId()),
                                document.getBoolean("disponivel"),
                                document.getDouble("ef"),
                                document.getString("empresa"),
                                document.getString("marca"),
                                document.getDouble("larg"),
                                document.getDouble("alt"),
                                document.getString("link"),
                                document.getDouble("pot"),
                                document.getDouble("valor")));
                    }
                } else {
                    Log.d("PAINEIS", "Error getting documents", task.getException());
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getContext(), "Error Painel" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        inversoresBD.collection("inversores").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {

                        inversores.add(new Inversor((document.getId()),
                                document.getDouble("alt"),
                                document.getDouble("larg"),
                                document.getDouble("ef"),
                                document.getDouble("potencia"),
                                document.getString("marca"),
                                document.getString("empresa"),
                                document.getString("link"),
                                document.getBoolean("disponivel")));
                        Log.d("INVERSORES", "ID:" + document.getId() + " => " + document.getData(), task.getException());
                    }
                } else {
                    Log.d("INVERSORES", "Error getting documents", task.getException());
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getContext(), "Error Inversor" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    // When I check my two List here their empty
    public void Calculate() {
        // Nothing relevant
    }
S. Souza
  • 110
  • 7
  • `Does anyone know why it is always the last process done?` not without seeing any code. Voting to close as too broad. – Matt Clark Mar 04 '18 at 18:55

1 Answers1

0

Does anyone know why it is always the last process done?

Because it's done asynchronously and you get response with a delay. You should calculate in onComplete as the last line of this method after the for loop to make sure list contains elements

    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (DocumentSnapshot document : task.getResult()) {

                            inversores.add(new Inversor((document.getId()),
                                    document.getDouble("alt"),
                                    document.getDouble("larg"),
                                    document.getDouble("ef"),
                                    document.getDouble("potencia"),
                                    document.getString("marca"),
                                    document.getString("empresa"),
                                    document.getString("link"),
                                    document.getBoolean("disponivel")));
                            Log.d("INVERSORES", "ID:" + document.getId() + " => " + document.getData(), task.getException());
                        }
                        calculate();    // call the mothod to calculate;
            } else {
                        Log.d("INVERSORES", "Error getting documents", task.getException());
                    }
                }
Rainmaker
  • 10,294
  • 9
  • 54
  • 89