How to execute requisitions in order?

3

I make 3 requests in a row, but they are triggered in order of processing, not synchronously, how can I solve this?

...

//botão pressionado
// primeira requisição

ivUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

             /* auto completes */

            txt_estados = (AutoCompleteTextView)
                    findViewById(R.id.txt_estado);
            txt_cidades = (AutoCompleteTextView)
                    findViewById(R.id.txt_cidade);
            txt_bairros = (AutoCompleteTextView)
                    findViewById(R.id.txt_bairro);

            final String estado = txt_estados.getText().toString().trim();
            final String cidade = txt_cidades.getText().toString().trim();
            final String bairro = txt_bairros.getText().toString().trim();
            final String metrosQ = txt_metrosQ.getText().toString().trim();
            final String quartos = txt_quartos.getText().toString().trim();
            final String garagens = txt_garagens.getText().toString().trim();
            final String cep = txt_cep.getText().toString().trim();
            final String complemento = txt_complemento.getText().toString().trim();
            final String preco = txt_preco.getText().toString().trim();
            final String descricao = txt_descricao.getText().toString().trim();
            final String map = txt_map.getText().toString().trim();

            final RadioGroup Rdtipo = (RadioGroup) findViewById(R.id.rd_tipo);
            int ntipo = Rdtipo.getCheckedRadioButtonId();


            if (ntipo == R.id.Apartamento) {
                tipo = "Apartamento";
            } else if (ntipo == R.id.Barracao) {
                tipo = "Barracão";
            }else if (ntipo == R.id.Residencial) {
                tipo = "Residêncial";
            }else if (ntipo == R.id.Terreno) {
                tipo = "Terreno";
            }else if (ntipo == R.id.Kitinete) {
                tipo = "Kitinete";
            }

            final RadioGroup RdtipoNeg = (RadioGroup) findViewById(R.id.rd_tipoNeg);
            int ntipoNeg = Rdtipo.getCheckedRadioButtonId();


            if (ntipoNeg == R.id.A) {
                tipoNeg = "A";
            } else if (ntipoNeg == R.id.C) {
                tipoNeg = "C";
            }

            final String idUser = "51"; // <-- aqui o id do usuario

            final MyCommand myCommander = new MyCommand(getApplicationContext());

            try{

                String url = "http://a4da1ea4.ngrok.io/upVariasImgs/solicitarAvaliacao.php";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();


                        idImovel = response;


                        responseList.add(response);

                        cadImgs(); <-- chamo a segunda requisição

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Erro ao fazer upload da imagem", Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<>();
                        params.put("metrosQ", metrosQ);
                        params.put("quartos", quartos);
                        params.put("garagens", garagens);
                        params.put("cep", cep);
                        params.put("complemento", complemento);
                        params.put("descricao", descricao);
                        params.put("mapa", map);
                        params.put("estado", estado);
                        params.put("cidade", cidade);
                        params.put("bairro", bairro);
                        params.put("tipo", tipo);
                        params.put("tipoNeg", tipoNeg);
                        params.put("preco", preco);
                        params.put("idUser", idUser);
                        return params;
                    }
                };

                myCommander.add(stringRequest);

            } catch (NullPointerException e) {
                Toast.makeText(getApplicationContext(), "Erro ao fazer upload da imagem", Toast.LENGTH_SHORT).show();
            }


            myCommander.execute();








        }
    });
}

When pressing the button ivUpload, the first request is triggered, where the property is stored in the bank and returned its id by json

//segunda requisição
public void cadImgs() {
    final MyCommand myCommand = new MyCommand(getApplicationContext());


    for(String imagePath: imageList){
        try {
            Bitmap bitmap = PhotoLoader.init().from(imagePath).requestSize(512, 512).getBitmap();
            final String encodedString = ImageBase64.encode(bitmap);


            String url = "http://a4da1ea4.ngrok.io/upVariasImgs/upload.php";
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();


                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(), "Erro ao fazer upload da imagem", Toast.LENGTH_SHORT).show();
                }
            }){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<>();
                    params.put("image", encodedString);
                    params.put("idImo", idImovel);
                    return params;
                }
            };

            myCommand.add(stringRequest);

        } catch (FileNotFoundException e) {
            Toast.makeText(getApplicationContext(), "Erro ao fazer upload da imagem", Toast.LENGTH_SHORT).show();
        }
    }


    myCommand.execute();
    somaId(); <-- está executando antes do loop acima
}


//terceira requisição
public void somaId(){
    ...
}

For this reason I did not call the third function somaId () on the server response, but after the loop ended, which causes it to break that order, and execute the somaId function, before the loop

    
asked by anonymous 30.03.2017 / 03:45

1 answer

3

From what is perceivable then one request is dependent on the other. In order for it to work in order correctly, you must call the next request only if the first request has already returned some result. As it is working asynchronously, running in processing mode, it does not have a specific time to finalize any type of query.

An example of problem solving is that you call a second request within your StringRequest , which in this case will only be executed at the end of the first request. See

StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String> () {
   @Override
   public void onResponse(String response) {

   // só será chamada a segunda requisição aqui dentro, pois já terá obtido a  resposta
   // da primeira requisição
   chamaSegundaRequisicao();
   }
}
    
30.03.2017 / 06:03