Using Loop to traverse an array, stopping at the first item and waiting for a click to the next JAVA item

Asked

Viewed 241 times

1

Good evening, folks, I’ve been trying to find a solution to my problem for three days without success. Let’s get to the problem.

I have an external API that is on a server, I can already make the connection with it for user validation and password, no problems. As soon as the user logs in with his USER he gets a list of tasks. So I have several task arrays, which will be assigned to the same user, and I’m looping through this array. What I need is: I need the loop to stop at the first ADDRESS_ID result, showing what the digit is - in this case the first ADDRESS_ID is 415 - and waiting for me to click on the screen to show the corresponding CHECK_DIGIT that is in the same array. (I will put my array at the end of the code). With this code I am posting, I can print on the screen only the last ADDRESS_ID of my list of Arrays. But again, I need it to stop at the first ADDRESS_ID and wait for me to tap the screen to bring up other information. Does anyone have any ideas? Thanks for the possible help!!!

public class activity_job extends AppCompatActivity {

    private static String URL = "http://minhaURL/app2/Api/NovaTarefa/";

    String recebeCodigo = "";
    int recCodigo = 0;

    TextView txtProd;
    TextView txtEnd;
    TextView txtQntProd;

    public String showUnidade;
    public String recebeUsuarioLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_job);

        txtProd = (TextView) findViewById(R.id.txtProduto);
        txtEnd = (TextView) findViewById(R.id.txtEndereco);
        txtQntProd = (TextView) findViewById(R.id.txtQntProduto);

        txtProd.setVisibility(View.INVISIBLE);
        txtEnd.setVisibility(View.INVISIBLE);
        txtQntProd.setVisibility(View.INVISIBLE);

        Bundle extras = getIntent().getExtras();

        if(extras != null){
            showUnidade = extras.getString("showUnidade");
            recebeUsuarioLogin = extras.getString("levaUsuario");
        }

        chamaApiProduto(recebeUsuarioLogin, showUnidade);

        //txtProd.setVisibility(View.VISIBLE);
        //txtProd.setText(showUnidade);
        //txtProd.setText(recebeUsuarioLogin);
    }

    private void chamaApiProduto(String BR, String unidade){
        URL = URL + BR + "/" + unidade + "/";

        StringRequest request = new StringRequest(URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try {
                    //A biblioteca do JSONObject serve para organizar novamente o que está dentro da variável 'response' em um formato JSON.
                    JSONObject reader = new JSONObject(response);

                    //Executando a leitura do JSON e buscando o campo 'CodigoErro'
                    recebeCodigo = reader.getString("CodigoErro");

                    recCodigo = Integer.parseInt(recebeCodigo);

                    //Lendo o que esta guardado no array 'Mensagem'
                    JSONArray trendsArray = reader.getJSONArray("Mensagem");

                    //
                    JSONObject trend;

                    //Criando um Array vazio para guardar os dados da 'Tarefa'
                    List<Tarefa> filaTarefa = new ArrayList<Tarefa>();


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

                        trend = new JSONObject(trendsArray.getString(i));

                        //Criando um objeto da classe usuario
                        Tarefa objetoTarefa = new Tarefa();

                        //Preenchendo o objeto 'objetoUsuario' com os dados do Array 'Mensagem'
                        objetoTarefa.BAY_ID = trend.getString("BAY_ID");
                        objetoTarefa.ADDRESS_ID = trend.getString("ADDRESS_ID");
                        objetoTarefa.CHECK_DIGIT = trend.getString("CHECK_DIGIT");
                        objetoTarefa.BOX_ASSIGNMENT = trend.getString("BOX_ASSIGNMENT");
                        objetoTarefa.PRODUCT_DESCRIPTION_SHORT = trend.getString("PRODUCT_DESCRIPTION_SHORT");
                        objetoTarefa.PRODUCT_DESCRIPTION_LONG = trend.getString("PRODUCT_DESCRIPTION_LONG");
                        objetoTarefa.PRODUCT_DESCRIPTION_PHONETIC = trend.getString("PRODUCT_DESCRIPTION_PHONETIC");

                        //Adicionando o objeto na lista de objetos usuarios
                        filaTarefa.add(objetoTarefa);

                    }

                    executaTarefa(filaTarefa);

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

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(activity_job.this, "Nao chegou", Toast.LENGTH_SHORT).show();
            }
        });
        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);
    }

    private void executaTarefa(List<Tarefa> filaTarefa){

        for (Tarefa obj : filaTarefa) {
            txtEnd.setVisibility(View.VISIBLE);
            txtEnd.setText(obj.ADDRESS_ID);
        }

    }
}

MY ARRAY

"Code": 1, "Message": [

    {
        "BAY_ID": "7",

        "ADDRESS_ID": "415",
        "CHECK_DIGIT": "865",
        "BOX_ASSIGNMENT": "206",
        "PRODUCT_DESCRIPTION_SHORT": "asdasdadsdas",
        "PRODUCT_DESCRIPTION_LONG": "asdasdadsdas asdasdadsd",
        "PRODUCT_DESCRIPTION_PHONETIC": "asdasdadsdas ",

    },
    {
        "BAY_ID": "7",

        "ADDRESS_ID": "412",
        "CHECK_DIGIT": "862",
        "BOX_ASSIGNMENT": "206",
        "PRODUCT_DESCRIPTION_SHORT": "asdasdadsdas",
        "PRODUCT_DESCRIPTION_LONG": "asdasdadsdas asdasdadsd",
        "PRODUCT_DESCRIPTION_PHONETIC": "asdasdadsdas ",

    },
    {
        "BAY_ID": "7",

        "ADDRESS_ID": "427",
        "CHECK_DIGIT": "877",
        "BOX_ASSIGNMENT": "206",
        "PRODUCT_DESCRIPTION_SHORT": "asdasdadsdas",
        "PRODUCT_DESCRIPTION_LONG": "asdasdadsdas asdasdadsd",
        "PRODUCT_DESCRIPTION_PHONETIC": "asdasdadsdas ",

    },
]

}

1 answer

1

Declares a variable to save the size of your list:

private int tamanhoLista = 0;
private List<Tarefa> filaTarefa = new ArrayList<>(); //Sua lista

//Preenchi para teste
filaTarefa.add(new Tarefa("415", "865"));
filaTarefa.add(new Tarefa("412", "862"));
filaTarefa.add(new Tarefa("427", "877"));

Assuming you have already verified that your API result has not returned null or empty.

//chama sua função a primeira vez exibindo o primeiro resultado
executaTarefa(0);

Its function that displays:

private void executaTarefa(int posicao){
    try{
        //Jogo o resultado na sua view ou onde deseja
        //txtEnd.setText(filaTarefa.get(posicao).getADDRESS_ID());

        //Vou exibir no logcat
        Log.i(TAG, "executaTarefa: "+filaTarefa.get(posicao).getADDRESS_ID());
    }catch(Exception ex){
        Log.e(TAG,"Erro na função executaTarefa: "+ex.getMessage());
    }
}

Afterward:

//Já no clique do seu botão (ou onde desejar) para exibir a próxima tarefa
    btnProsseguir.setOnClickListener(v -> {
        //Somo mais 1, logo, irá exibir o segundo item na sua lista de tarefa
        tamanhoLista += 1;

        if(tamanhoLista < filaTarefa.size()){
            //chama sua função novamente
            executaTarefa(tamanhoLista);
        }else{
            //Toast.makeText(this, "Não tem mais tarefas!", Toast.LENGTH_SHORT).show();
            Log.i(TAG, "Não tem mais tarefas!");
        }
    });

Output in my log:

inserir a descrição da imagem aqui

P.S.: Remembering that you can use break; for a loop, but then the logic would be different than the one I posted, good luck there.

  • Wonderful, man. I made it a little different but the logic was just that. Thank you very much. Abs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.