Standard value in Spinner+ generated from the database

Asked

Viewed 89 times

1

I have a spinner that pulls the bank values, but I would like to leave it with nothing selected or default value:

public void spinnerClientes() {
        ControllerClientes ctClientes = new ControllerClientes(this);
        ArrayList<ArrayCliente> clientes = ctClientes.getClientes();
        clientes.add(new ArrayCliente(0, "Selecione..."));
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, clientes);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnClientes.setAdapter(adapter);
}

The problem is that trying to create the default value clientes.add(new ArrayCliente(0, "Selecione...")); this value is added only at the end of the list.

I’ve tried that way too, but it doesn’t generate value because it’s replaced:

ArrayList<ArrayCliente> clientes = ArrayList<>();
clientes.add(new ArrayCliente(0, "Selecione..."));
clientes = ctClientes.getClientes();

2 answers

2


You must first add the "Select..." item and then return the method getClientes() using addAll().

public void spinnerClientes() {
    ControllerClientes ctClientes = new ControllerClientes(this);
    ArrayList<ArrayCliente> clientes = new ArrayList<>();
    clientes.add(new ArrayCliente(0, "Selecione..."));
    clientes.addAll(ctClientes.getClientes());           
    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, clientes);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spnClientes.setAdapter(adapter);
}
  • It worked perfectly, but I found the @Isac way more practical ! Thank you !

  • 1

    Possibly more practical but with less performance :).

  • So I’m going to use this way, one less item to lower performance !

1

Giving only another alternative to the @ramaral solution, you can use a Overload of the method Add which you were using which you also receive the position where you will add.

The signature of this method is add(int index,E element), in which index is the position and element is the element to be added.

Your code would look like this:

public void spinnerClientes() {
    ControllerClientes ctClientes = new ControllerClientes(this);
    ArrayList<ArrayCliente> clientes = ctClientes.getClientes();
    clientes.add(0, new ArrayCliente(0, "Selecione..."));
    //-----------^ adicionar na posição 0 do array de clientes
    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, clientes);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spnClientes.setAdapter(adapter);
}

Documentation for the add(int index,E element)

  • Working ! Thank you !

Browser other questions tagged

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