Jump to content

Spinner com Key e Value igual a Select


Carlos Rocha

Recommended Posts

Pessoal, com o código abaixo eu populo um Spiiner;

Esse Spinner, é populado por um atributo de um Array de objetos

À principio, temos o seguinte JSONArray:

[
  {
    "id":"1",
  "nome":"Carlos"
  }, 
  {
    "id":"2",
  "nome":"Cleonice Rocha"
  }, 
  {
    "id":"3",
  "nome":"Cleonice Rocha"
  }
]

Agora temos o método:

private void preencheComboClientes(JSONArray jsClientes) throws JSONException {

    JSONObject jsonObject;

    final HashMap<Integer, String> listaClientes = new HashMap<Integer, String>();

    for (Integer i = 0; i < jsClientes.length(); i++) {

        jsonObject = jsClientes.getJSONObject(i).getJSONObject("cliente");

        Integer id = jsonObject.getInt("id");
        String nome = jsonObject.getString("nome");

        listaClientes.put(id, nome);

    }

    List<StringWithTag> itemList = new ArrayList<StringWithTag>();

    for (Map.Entry<Integer, String> entry : listaClientes.entrySet()) {

        Integer key = entry.getKey();
        String value = entry.getValue();

        itemList.add(new StringWithTag(value, key));

    }

    spinnerAdapterClientes = new ArrayAdapter<StringWithTag>(this, android.R.layout.simple_spinner_item, itemList);
    spinnerAdapterClientes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spCliente.setAdapter(spinnerAdapterClientes);


    spCliente.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            for (Map.Entry<Integer, String> entry : listaClientes.entrySet()) {

                Integer key = entry.getKey();
                String value = entry.getValue();

                if (parent.getSelectedItem().toString().equals(value)) {
                    Log.i("Achei!!!" , Integer.toString(key));
                }

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

            // sometimes you need nothing here
        }
    });

}


Então, imagine a situação em que você tem um Array de Objetos e esse Objeto possui CPF e NOME

Bom,
 CPF cada um tem o seu. Não se repete.
Mas,
 Nome, infelizmente podemos ter 2 nomes iguais

Logo, não posso enviar a consulta por nome e sim por CPF
Como o Spinner não aceita CPF e Nome, logo, fico impossibilitado de fazer conferências.

Como vocês fazer nesse caso?

Edited by carcleo
Link to comment
Share on other sites

Viva,

1) No seu "spinner" consegues colocar o que quiser, mesmo assumindo a forma + simples (android.R.layout.simple_spinner_item), podes sempre mostrar o nome + cpf:

private static class StringWithTag {
    public String string;
    public String cpf;
    public Object tag;

    public StringWithTag(String string, String cpf, Object tag) {
        this.string = string;
        this.cpf = cpf;
        this.tag = tag;
    }

    @Override
    public String toString() {
        return string + "(" + cpf + ")";
    }
}

Podes sempre customizar o "layout" (android.R.layout.simple_spinner_item) e fazer o teu próprio.

2) O seu outro problema... a meu ver um "spinner" para seleccionar pessoas (clientes?) não parece boa ideia, porque será uma lista bem bem extensa.

Se fosse eu faria uma segunda "janela" (ou popup) com um "RecyclerView" de todos os clientes + EditText de pesquisa filtro por parte do "nome, cpf, telefone, email, ..."

Não só + visualmente podemos ver vários dados do cliente, + podemos filtrar/encontrar por vários campos, não importa a quantidade de clientes e funcionará com poucos ou muitos.

cps,

AS

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.