Check if there is already value inside the Array and listview?

Asked

Viewed 38 times

-2

How can I make sure that no values are repeated inside the Array and listview? I’m making an app for "registration" code. It has an Edittext, and a send button, when clicking it takes this Edittext code and plays for Listview.

I’m using if (listaCodigos.contains(codigo))

But it’s not working. What am I doing wrong?

inserir a descrição da imagem aqui

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    List<String> listaCodigos = new ArrayList<String>();

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

    public void alteraLista(View view) {

        EditText campoCodigo = findViewById(R.id.idCodigo);
        String codigo = campoCodigo.getText().toString();

        //Verificando se o campo esta vazio
        if (campoCodigo.getText().toString().equals("")) {
            Toast toast = Toast.makeText(getApplicationContext(), "Campo Codigo Vazio", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();

            //Verificando se o codigo ja existe
        } else {
            if (listaCodigos.contains(codigo)) {
                Toast toast = Toast.makeText(getApplicationContext(), "Codigo ja existe", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();

            } else {
                listaCodigos.add("Codigo: " + codigo);
                Toast toast = Toast.makeText(getApplicationContext(), "Codigo Adicionado", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        }

        ListView lista = findViewById(R.id.listView);

        ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listaCodigos);
        lista.setAdapter(adaptador);
        campoCodigo.setText("");
    }
}
    

1 answer

0


In the following section of your code, you do not only add the variable codigo to the list, but rather a concatenation of it:

listaCodigos.add("Codigo: " + codigo);

Therefore, for her condition to work she should be:

if (listaCodigos.contains("Codigo: " + codigo)) {
  • Our was on my face and I couldn’t see it! Thank you so much! I only had to put the text between relatives 'if (listCodigos.contains(("Code: ") + code)) {'

Browser other questions tagged

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