【问题标题】:How to get selected item in Spinner如何在 Spinner 中获取所选项目
【发布时间】:2015-05-27 20:43:32
【问题描述】:

我一直在这个圈子里兜圈子。如果它与数据库中的记录匹配,我已设法将微调器设置为在列表中显示项目,但现在在我保存记录时从微调器获取所选项目时出现问题。相反,我得到了类似'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();
    }

}

【问题讨论】:

  • 你有没有在 logcat 中发现任何错误?
  • 嗨沙拉特。不,它只是输入到数据库字段中,例如“android.database.sqlite.SQLiteCursor@44fa41b0”,而不是微调器显示的字符串值..
  • 尝试遵循 Ridcully 的建议。如果它没有解决问题,我们会再看看
  • 很高兴听到并感谢您的告知。

标签: android android-spinner


【解决方案1】:

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

编辑

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

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

【讨论】:

  • 这会导致数据库往返吗?因此意味着它可以锁定 UIThread...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 2013-08-29
  • 1970-01-01
相关资源
最近更新 更多