Default value in Spinner + generated from bank

1

I have a spinner that pulls the values from the bank but 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 only added at the end of the list.

I have also tried this way, but it does not generate the value because it is replaced:

ArrayList<ArrayCliente> clientes = ArrayList<>();
clientes.add(new ArrayCliente(0, "Selecione..."));
clientes = ctClientes.getClientes();
    
asked by anonymous 30.01.2018 / 10:52

2 answers

2

You should first add the "Select ..." item and then return the getClientes() method 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);
}
    
30.01.2018 / 13:24
1

By giving only one alternative to the @ramaral solution, you can use an overload of the Add method you were using which also gets the position where you add it.

The signature of this method is add(int index,E element) , where index is position and element is the element to add.

In your code it 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 add(int index,E element)

    
30.01.2018 / 13:29