alois.wirkes
alois.wirkes

Reputation: 369

Add a "Please Select" option to a Spinner in Android

I have a Spinner which is filled from a query using a SimpleCursorAdapter, this works fine... but now I need to put an option "Please Select" before all the items retrieved from the query, just for usability issues... but I'm not quite sure of how to do so... HELP please...


Here is my code...

private Spinner comboForm;
...
comboForm = (Spinner) findViewById(R.id.comboFormularios);
...
mDbH.abrir();
final Cursor cu = mDbH.consultaFormularios(idU);
if(cu.moveToFirst() == false){
    cu.close();
    mDbH.cerrar();
}else{
    SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(getApplicationContext(),R.layout.spinner,cu,new String[] {"nombre"},new int[] {R.id.textoCombo});
    adapter2.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
    comboForm.setAdapter(adapter2);
}
mDbH.cerrar();
...
comboForm.setOnItemSelectedListener(new OnItemSelectedListener(){
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView,int position, long id) {
        idF = (int) id;
        obtenerDatosRutas(idU,idF);
        tabla.removeAllViews();
        llenarTabla();
    }

    public void onNothingSelected(AdapterView<?> arg0) {}
});

Where mDbH is an instance of the class I'm using to manipulate the Database... as you can see the Spinner is filled up from Cursor resulting of the query consultaFormularios(idU)

Upvotes: 1

Views: 2053

Answers (1)

JustDanyul
JustDanyul

Reputation: 14054

When you create your cursor, one possible solution would be to use a SQL UNION and construct second SELECT that simply contains the label you need (adding hard-coded dummy fields for ordering).

Alternatively, and this is most likely the simplest solution. Instead of using a cursor adapter, use an array adapter and start by populating the array with your default value you want, then stick in all the items from your cursor. Something like,

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Please select");

final Cursor cu = mDbH.consultaFormularios(idU);

while(cu.moveToNext()) { 
    arrayList.add(cu.getString(0)); // assuming you want a 
                                    //string from the first column
}

ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, arrayList);
comboForm.setAdapter(spinnerArrayAdapter);

Upvotes: 1

Related Questions