如何在Spinner中对数据进行排序

时间:2012-10-04 18:18:22

标签: database sorting spinner

我有许多从数据库表中填充的微调器。我想控制数据在微调器中的排序方式,如下例所示:我有以下形式的数据:

1,2,3,4,5,6,7,8,9,10,11,12等

但是这个由微调器按照这样排序:

1,10,11,12,13,14,15,16,17,18,19,2,20,21等

显然不对!

我的Spinner代码的示例(不是上面的Spinner),如下所示:

    Cursor componentCursor = rmDbHelper.fetchAllComponents();
    startManagingCursor(componentCursor);

    // create an array to specify which fields we want to display
    String[] from2 = new String[]{RMDbAdapter.COMPONENT_FORM_TEXT};
    //INSPECTOR_NAME = "inspector_name"
    // create an array of the display item we want to bind our data to
    int[] to2 = new int[]{android.R.id.text1};
    // create simple cursor adapter
    SimpleCursorAdapter componentSpinnerAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, componentCursor, from2, to2 );
    componentSpinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
    // get reference to our spinner
    componentSpinner.setAdapter(componentSpinnerAdapter);
    if (locationId > 0) { // Set spinner to match saved data in database

        int spinnerPosition = 0; 

        for (int i = 0; i < componentSpinner.getCount(); i++)  
        { 
             Cursor cur = (Cursor)(componentSpinner.getItemAtPosition(i)); 

             //--When your bind you data to the spinner to begin with, whatever columns you 
             //--used you will need to reference it in the cursors getString() method... 

             //--Since "getString()" returns the value of the requested column as a String--  
             //--(In my case) the 4th column of my spinner contained all of my text values  
             //--hence why I set the index of "getString()" method to "getString(3)" 

             String componentSpinnerString = cur.getString(2).toString(); 

             if(componentSpinnerString.equals(componentSpinnerData.toString())) 
             { 
                //--get the spinner position-- 
                spinnerPosition = i; 
                break; 
              } 
         }       
        componentSpinner.setSelection(spinnerPosition); 
    }

    else { // Set spinner to default

        int spinnerPosition = 0; 

        for (int i = 0; i < componentSpinner.getCount(); i++)  
        { 
            Cursor cur = (Cursor)(componentSpinner.getItemAtPosition(i));

            String componentSpinnerString = cur.getString(2).toString();

            if(componentSpinnerString.equals("Upright (front)"))
            { 
                //--get the spinner position-- 
                spinnerPosition = i; 
                break; 
            } 
         }       
        componentSpinner.setSelection(spinnerPosition);

    }

下面的数据库代码(根据gotuskar的要求):

public Cursor fetchAllComponents() {
    return rmDb.query(COMPONENT_TABLE, new String[] {
            COMPONENT_ID, RACKING_SYSTEM, COMPONENT_FORM_TEXT, TEXT_BOXES_DATA},
            null, null, null, null, null);
}

0 个答案:

没有答案