如何在Spinner中获取所选项目

时间:2012-09-03 18:15:57

标签: android android-spinner

我一直围着这个圈子走。如果它与数据库中的记录匹配,我已设法将微调器设置为显示列表中的项目,但现在在保存记录时从微调器获取所选项目时出现问题。我改为像'android.database.sqlite.SQLiteCursor@44fa41b0'。

在我的saveInspection()方法中,我使用的是inspectedBySpinner.getSelectedItem()。toString(); (详见本文How do you get the selected value of a Spinner?中的第二个答案)但没有成功..(如此接近但没有香蕉!)。

我确信这是显而易见的事情,但非常感谢:

public class InspectionEdit extends Activity {

final Context context = this;

private EditText inspectionReferenceEditText;
private EditText inspectionCompanyEditText;
private Button inspectionDateButton;
private Spinner inspectedBySpinner;
private Button saveButton;
private Button cancelButton;
protected boolean changesMade;
private AlertDialog unsavedChangesDialog;
private Button addInspectorButton;

private int mYear;
private int mMonth;
private int mDay;
private StringBuilder mToday;
private RMDbAdapter rmDbHelper;
private long inspectionId;

private String inspectedBySpinnerData;

//private String inspectors;

static final int DATE_DIALOG_ID = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    rmDbHelper = new RMDbAdapter(this);
    rmDbHelper.open();
    Intent i = getIntent();
    inspectionId = i.getLongExtra("Intent_InspectionID", -1);
    setContentView(R.layout.edit_inspection);
    setUpViews();
    populateFields();
    fillSpinner();
    setTextChangedListeners();

}

private void setUpViews() {
    inspectionReferenceEditText =(EditText)findViewById(R.id.inspection_reference);
    inspectionCompanyEditText =(EditText)findViewById(R.id.inspection_company);
    inspectionDateButton =(Button)findViewById(R.id.inspection_date);
    inspectedBySpinner =(Spinner)findViewById(R.id.inspected_by_spinner);

    addInspectorButton = (Button)findViewById(R.id.add_inspector_button);
    saveButton = (Button)findViewById(R.id.inspection_save_button);
    cancelButton = (Button)findViewById(R.id.inspection_cancel_button);
}

 private void populateFields() {
        if (inspectionId > 0) {
            Cursor inspectionCursor = rmDbHelper.fetchInspection(inspectionId);
            startManagingCursor(inspectionCursor);
            inspectionReferenceEditText.setText(inspectionCursor.getString(
                    inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_REF)));
            inspectionCompanyEditText.setText(inspectionCursor.getString(
                    inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_COMPANY)));
            inspectionDateButton.setText(inspectionCursor.getString(
                    inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_DATE)));
            inspectedBySpinnerData = inspectionCursor.getString(
                    inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_BY));

            Toast.makeText(getApplicationContext(), inspectedBySpinnerData, 
                 Toast.LENGTH_LONG).show();
        }
    }

private void fillSpinner() {

    Cursor inspectorCursor = rmDbHelper.fetchAllInspectors();
    startManagingCursor(inspectorCursor);

    // create an array to specify which fields we want to display
    String[] from = new String[]{RMDbAdapter.INSPECTOR_NAME};
    //INSPECTOR_NAME = "inspector_name"
    // create an array of the display item we want to bind our data to
    int[] to = new int[]{android.R.id.text1};
    // create simple cursor adapter
    SimpleCursorAdapter spinnerAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, inspectorCursor, from, to );
    spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
    // get reference to our spinner
    inspectedBySpinner.setAdapter(spinnerAdapter);
    if (inspectionId > 0) {

        int spinnerPosition = 0; 

        for (int i = 0; i < inspectedBySpinner.getCount(); i++)  
        { 
             Cursor cur = (Cursor)(inspectedBySpinner.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 currentSpinnerString = cur.getString(1).toString(); 

             if(currentSpinnerString.equals(inspectedBySpinnerData.toString())) 
             { 
                //--get the spinner position-- 
                spinnerPosition = i; 
                break; 
              } 
         }       
         inspectedBySpinner.setSelection(spinnerPosition); 
    }

}


 private void addInspector() {
    // get prompts.xml view
    LayoutInflater li = LayoutInflater.from(context);
    View promptsView = li.inflate(R.layout.prompt_dialog, null);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            context);

    // set prompts.xml to alertdialog builder
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView
            .findViewById(R.id.editTextDialogUserInput);

    // set dialog message
    alertDialogBuilder
        .setCancelable(false)
        .setPositiveButton("OK",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
            // get user input and set it to result
            // edit text
            String inspector = userInput.getText().toString();
            rmDbHelper.createInspector(inspector);

            }
          })
        .setNegativeButton("Cancel",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
            dialog.cancel();
            }
          });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
 }

private void setTextChangedListeners() {
     changesMade = false;

     inspectionReferenceEditText.addTextChangedListener(new TextWatcher(){
         public void afterTextChanged(Editable s) {
         }
         public void beforeTextChanged(CharSequence s, int start, int count, int after) {
         }
         public void onTextChanged(CharSequence s, int start, int before, int count) {
             changesMade = true;
         }  
    });

     inspectionCompanyEditText.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable s) {
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            changesMade = true;
        }   
    }); 

     inspectionDateButton.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable s) {
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            changesMade = true;
        }   
    });

    inspectionDateButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
        }
    });

    addInspectorButton.setOnClickListener(new View.OnClickListener() {                      
        public void onClick(View v) {
            addInspector();
        }
    });

    saveButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            saveInspection();
            finish();
        }
    });

    cancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
        cancel();
        }
    });
  }

protected void saveInspection() {
    String reference = inspectionReferenceEditText.getText().toString();
    String companyName = inspectionCompanyEditText.getText().toString();
    String inspectionDate = RMUtilities.compareTwoStringsNullIfSame(inspectionDateButton.getText().toString(), "Click to add");
    String inspectedBy = inspectedBySpinner.getSelectedItem().toString();
    Toast.makeText(getApplicationContext(), inspectedBy, 
            Toast.LENGTH_LONG).show();
    if (inspectionId > 0) {
        rmDbHelper.updateInspection(inspectionId, reference, companyName, inspectionDate, inspectedBy);
        Toast.makeText(getApplicationContext(), "Inspection updated", 
                Toast.LENGTH_LONG).show();
    }
    else {
        rmDbHelper.createInspection(reference, companyName, inspectionDate, inspectedBy);
        Toast.makeText(getApplicationContext(), "Inspection created", 
                Toast.LENGTH_LONG).show();
    }

}

1 个答案:

答案 0 :(得分:6)

当您使用CursorAdapter而不是基于List或String数组的适配器时,您必须使用Cursor来获取所选项的值。 Spinner的getSelectedItem将调用CursorAdapter的getItem(position),它将返回Cursor对象。因此,使用toString(),首先将返回的对象强制转换为Cursor,然后使用Cursor的get...方法获取所选项目的所需数据。

修改

根据你填充你的微调器的方式,你可能需要这个:

String inspectedBy = ((Cursor)inspectedBySpinner.getSelectedItem())
                        .getString(1).toString();