13

I have a Spinner which gets populate using a SimpleCursorAdapter. My cursor has some values, but i need the Spinner to show an empty option by default.

I don't want to use ArrayAdapter<String>, or CursorWrapper in this app, for some reason.

There should be a simpler way to show an empty option in the Spinner by default.

Macarse
  • 91,829
  • 44
  • 175
  • 230
AAP
  • 235
  • 1
  • 3
  • 9
  • here is link how you might do it (adding a dummy item) https://www.youtube.com/watch?v=FcMiw16bouA – Abdu Oct 13 '18 at 17:02

5 Answers5

5

You can simply hide the unwanted view in the spinner adapter (getDropDownView ) :

In my sample code, defaultposition is the position to hide (like a "Select value" position)

public class SpinnerOptionAdapter extends ArrayAdapter<optionsInfos> {

 ...

   @Override

  public View getDropDownView(int position, View convertView, ViewGroup parent)
  {   // This view starts when we click the spinner.
    View row = convertView;
    if(row == null)
    {
        LayoutInflater inflater = context.getLayoutInflater();
        row = inflater.inflate(R.layout.product_tab_produit_spinner_layout, parent, false);
    }

    ...

    optionsInfos item = data.get(position);


    if( (item != null) && ( position == defaultposition)) {
        row.setVisibility(View.GONE);
    } else {
        row.setVisibility(View.VISIBLE);
    }

   ....

    return row;
}


 ...
}
Verbeia
  • 4,400
  • 2
  • 23
  • 44
Ralph
  • 51
  • 1
  • 2
  • I understand. But you must have a null ítem, and I haven't it in my db. that's the real problema. – AAP Apr 29 '12 at 18:56
2

A method I sometimes use to add an extra record such as an "empty" option with a SimpleCursorAdapter destined for a Spinner is by using a UNION clause in my cursor query. EMPTY_SPINNER_STRING could be something like: "-- none specified --" or similar. Use an "order by" clause to get your empty record first and therefore the default value in the Spinner. A crude but effective way of getting the required result without changing the underlying table data. In my example I only want certain spinners to have a default empty value (those with a modifier type of "intensity".

public Cursor getLOV(String modifier_type)
//get the list of values (LOVS) for a given modifier
{
    if (mDb == null)
    {
        this.open();
    }
    try {
        MYSQL = "SELECT _ID AS '_id', code, name, type as 'DESC', ordering FROM "+codeTab+" WHERE type = '"+modifier_type+"'" +
                " ORDER BY ordering, LOWER(name)";
        if (modifier_type.equals("intensity")) { //then include a default empty record
            MYSQL = "SELECT _ID AS '_id', code, name as 'NAME', type as 'DESC', ordering FROM "+codeTab+" WHERE type = '"+modifier_type+"'" +
                    " UNION SELECT 9999 AS '_id', '' AS 'code', '"+EMPTY_SPINNER_STRING+"' AS 'NAME', 'intensity' AS 'DESC', 1 AS ordering ORDER BY ordering, name";
        }
        Log.d(TAG, "MYSQL = "+MYSQL);
        return mDb.rawQuery(MYSQL, null);
    }
    catch (SQLiteException exception) {
        Log.e("Database LOV query", exception.getLocalizedMessage());
        return null;
    }
}
laurie_v
  • 21
  • 3
2

Spinner's OnItemSelectedListener runs on the compile time as well that fetches the first item to view on the Spinner selected item.

Add a dummy item (String - null " ") on your SimpleCursorAdapter and use spinner.setSelected(int thatSpecificPostionYouJustAdded).

Macarse
  • 91,829
  • 44
  • 175
  • 230
IronBlossom
  • 3,898
  • 3
  • 35
  • 42
  • A ArrayAdapter have an 'add' method, but the SimpleCursorAdapter haven´t it. Could you explain how add a null value with code, without using CursorWrapper?. Thanks – AAP Jan 30 '12 at 13:52
  • Sorry for being late, may be [this](http://stackoverflow.com/questions/8508678/how-to-add-an-item-to-simplecursoradapter) will help somehow. – IronBlossom Jan 31 '12 at 07:04
0

After setting the adapter. call setSelection (i used with 0) and right after that set the text color to transparent.

    // Preselect the first to make the spinner text transparent
    spinner.setSelection(0, false);
    TextView selectedView = (TextView) spinner.getSelectedView();
    if (selectedView != null) {
        selectedView.setTextColor(getResources().getColor(R.color.transparent));
    }

Then, set your OnItemSelectedListener (if needed).

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        }

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

This will make the spinner empty at first time seen. But, if the user will select the first item it will do nothing because 0 is pre selected. For fixing this i used this subclass of spinner. taken from @melquiades's answer:


/** 
  * Spinner extension that calls onItemSelected even when the selection is the same as its previous value
  */
public class FVRSpinner extends Spinner {

    public FVRSpinner(Context context) {
        super(context);
    }

    public FVRSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FVRSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setSelection(int position, boolean animate) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position, animate);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }

    @Override
    public void setSelection(int position) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }
}
Community
  • 1
  • 1
Shirane85
  • 2,255
  • 1
  • 26
  • 38
0

Create a NullSpinnerItem class and inject it at the start of the list.

// Class to represent the `null` selection in a List of items in a Spinner.
// There is no easy way to tell Spinner to also include a blank or null value. 
// This allows us to inject this as the first item in the List and handle null values easily.
//
public class NullSpinnerItem {

  @Override
  public String toString() {
    return "None";
  }

}

Then when you're populating your spinner, just get your items and then add it to the first position:

items.add( 0, new NullSpinnerItem() ); // items are your items.

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource( R.layout.spinner_list_item);

Spinner spinner = (Spinner) findViewById(spinnerId);
spinner.setAdapter(adapter);

The toString() method is what is displayed in the Spinner.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245