如何微调得到所选项目 [英] How to get selected item in Spinner

查看:148
本文介绍了如何微调得到所选项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直转圈圈这一个。我已成功地设置微调在列表中显示的项目,如果它在数据库中的记录匹配,但现在有一个问题,从微调获得所选择的项目,当我保存记录。我反而得到的东西像'android.database.sqlite.SQLiteCursor@44fa41b0。

在我saveInspection()方法中,我使用inspectedBySpinner.getSelectedItem()的toString(); (在这个帖子<详细的在第二个答案href=\"http://stackoverflow.com/questions/2652414/how-do-you-get-the-selected-value-of-a-spinner-android\">How你得到一个微调的设定值 - !没有成功。(这么近还没有香蕉的Andr​​oid ))。

我敢肯定这是一件弗利明显,但帮助不大AP preciated:

 公共类InspectionEdit延伸活动{最后上下文的背景下=这;私人的EditText inspectionReferenceEditText;
私人的EditText inspectionCompanyEditText;
私人按钮inspectionDateButton;
私人微调inspectedBySpinner;
私人按钮saveButton;
私人按钮cancelButton;
保护布尔changesMade;
私人AlertDialog unsavedChangesDialog;
私人按钮addInspectorButton;私人诠释mYear;
私人诠释mMonth;
私人诠释MDAY;
私人StringBuilder的mToday;
私人RMDbAdapter rmDbHelper;
私人长期inspectionId;私人字符串inspectedBySpinnerData;//私人字符串督察;静态最终诠释DATE_DIALOG_ID = 0;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    rmDbHelper =新RMDbAdapter(本);
    rmDbHelper.open();
    意向I = getIntent();
    inspectionId = i.getLongExtra(Intent_InspectionID,-1);
    的setContentView(R.layout.edit_inspection);
    setUpViews();
    populateFields();
    fillSpinner();
    setTextChangedListeners();}私人无效setUpViews(){
    inspectionReferenceEditText =(EditText上)findViewById(R.id.inspection_reference);
    inspectionCompanyEditText =(EditText上)findViewById(R.id.inspection_company);
    inspectionDateButton =(按钮)findViewById(R.id.inspection_date);
    inspectedBySpinner =(微调)findViewById(R.id.inspected_by_spinner);    addInspectorButton =(按钮)findViewById(R.id.add_inspector_button);
    saveButton =(按钮)findViewById(R.id.inspection_save_button);
    cancelButton =(按钮)findViewById(R.id.inspection_cancel_button);
} 私人无效populateFields(){
        如果(inspectionId大于0){
            光标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();
        }
    }私人无效fillSpinner(){    光标inspectorCursor = rmDbHelper.fetchAllInspectors();
    startManagingCursor(inspectorCursor);    //创建一个数组来指定我们要显示的字段
    的String [] =由新的String [] {} RMDbAdapter.INSPECTOR_NAME;
    // INSPECTOR_NAME =inspector_name
    //创建我们要我们的数据绑定到显示项目的数组
    INT []为= INT新[] {} android.R.id.text1;
    //创建简单的游标适配器
    SimpleCursorAdapter spinnerAdapter =新SimpleCursorAdapter(这一点,android.R.layout.simple_spinner_item,inspectorCursor,从,到);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    //获取参考我们微调
    inspectedBySpinner.setAdapter(spinnerAdapter);
    如果(inspectionId大于0){        INT spinnerPosition = 0;        的for(int i = 0; I&LT; inspectedBySpinner.getCount();我++)
        {
             光标CUR =(光标)(inspectedBySpinner.getItemAtPosition(I));             // - 当你的绑定您的数据微调,首先,不管你列
             // - 用你需要引用它在光标getString()方法...             // - 由于的getString()返回作为String--请求列的值
             // - (对我来说)我的飞旋的第4列包含了所有我的文字值
             // - 因此为什么我设置的getString()方法的指数的getString(3)             串currentSpinnerString = cur.getString(1)的ToString();             如果(currentSpinnerString.equals(inspectedBySpinnerData.toString()))
             {
                // - 得到微调position--
                spinnerPosition = I;
                打破;
              }
         }
         inspectedBySpinner.setSelection(spinnerPosition);
    }}
 私人无效addInspector(){
    //获取prompts.xml视图
    LayoutInflater李= LayoutInflater.from(背景);
    查看promptsView = li.inflate(R.layout.prompt_dialog,NULL);    AlertDialog.Builder alertDialogBu​​ilder =新AlertDialog.Builder(
            背景);    //设置prompts.xml为alertdialog建设者
    alertDialogBu​​ilder.setView(promptsView);    最终的EditText userInput =(EditText上)promptsView
            .findViewById(R.id.editTextDialogUserInput);    //设置对话框消息
    alertDialogBu​​ilder
        .setCancelable(假)
        .setPositiveButton(OK,
          新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释的id){
            //获取用户输入,并将其设置导致
            //编辑文本
            。字符串督察= userInput.getText()的toString();
            rmDbHelper.createInspector(检查员);            }
          })
        .setNegativeButton(取消,
          新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释的id){
            dialog.cancel();
            }
          });    //创建警报对话框
    AlertDialog alertDialog = alertDialogBu​​ilder.create();    // 展示下
    alertDialog.show();
 }私人无效setTextChangedListeners(){
     changesMade = FALSE;     inspectionReferenceEditText.addTextChangedListener(新TextWatcher(){
         公共无效afterTextChanged(编辑S){
         }
         公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数后INT){
         }
         公共无效onTextChanged(CharSequence中,诠释开始,诠释之前,诠释计数){
             changesMade =真;
         }
    });     inspectionCompanyEditText.addTextChangedListener(新TextWatcher(){
        公共无效afterTextChanged(编辑S){
        }
        公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数后INT){
        }
        公共无效onTextChanged(CharSequence中,诠释开始,诠释之前,诠释计数){
            changesMade =真;
        }
    });     inspectionDateButton.addTextChangedListener(新TextWatcher(){
        公共无效afterTextChanged(编辑S){
        }
        公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数后INT){
        }
        公共无效onTextChanged(CharSequence中,诠释开始,诠释之前,诠释计数){
            changesMade =真;
        }
    });    inspectionDateButton.setOnClickListener(新View.OnClickListener(){
        公共无效的onClick(视图v){
            的ShowDialog(DATE_DIALOG_ID);
        }
    });    addInspectorButton.setOnClickListener(新View.OnClickListener(){
        公共无效的onClick(视图v){
            addInspector();
        }
    });    saveButton.setOnClickListener(新View.OnClickListener(){
        公共无效的onClick(视图v){
            saveInspection();
            完();
        }
    });    cancelButton.setOnClickListener(新View.OnClickListener(){
        公共无效的onClick(视图v){
        取消();
        }
    });
  }保护无效saveInspection(){
    String引用= inspectionReferenceEditText.getText()的toString()。
    字符串的companyName = inspectionCompanyEditText.getText()的toString()。
    字符串inspectionDate = RMUtilities.compareTwoStringsNullIfSame(inspectionDateButton.getText()的toString(),点击添加。);
    字符串inspectedBy = inspectedBySpinner.getSelectedItem()的toString()。
    Toast.makeText(getApplicationContext(),inspectedBy,
            Toast.LENGTH_LONG).show();
    如果(inspectionId大于0){
        rmDbHelper.updateInspection(inspectionId,参考,公司名称,inspectionDate,inspectedBy);
        Toast.makeText(getApplicationContext(),检查更新,
                Toast.LENGTH_LONG).show();
    }
    其他{
        rmDbHelper.createInspection(参考,公司名称,inspectionDate,inspectedBy);
        Toast.makeText(getApplicationContext(),检查创建
                Toast.LENGTH_LONG).show();
    }}


解决方案

当您使用的CursorAdapter 而不是适配器基于字符​​串列表或数组,你'将不得不使用光标来获取所选项目的值。 Spinner的 getSelectedItem 将调用的CursorAdapter的的getItem(位置)这将返回光标对象。因此,而不是使用的toString(),先投返回的对象为光标,然后使用游标的的get ... 的方法来获取所选项目的所需的数据。

修改

根据您如何填写你微调你可能需要这样的:

 字符串inspectedBy =((光标)inspectedBySpinner.getSelectedItem())
                        .getString(1)的ToString();

I keep going round in circles with this one. I have managed to set the spinner to show item in the list if it matches a record in the database, but now have an issue with getting the selected item from the spinner when I save the record. I instead get something like 'android.database.sqlite.SQLiteCursor@44fa41b0'.

In my saveInspection() method, I am using inspectedBySpinner.getSelectedItem().toString(); (as detailed in second answer in this post How do you get the selected value of a spinner -- Android) with no success.. (so close yet no banana!).

I'm sure this is something flippin obvious, but help much appreciated:

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();
    }

}

解决方案

As you use a CursorAdapter and not an Adapter based on a List or Array of String, you'll have to use the Cursor to fetch the value of the selected item. The Spinner's getSelectedItem will call the CursorAdapter's getItem(position) which will return the Cursor object. So instead to using toString(), first cast the returned object to a Cursor and then use Cursor's get... methods to fetch the required data of the selected item.

EDIT

Based on how you fill your spinner you'll probably need this:

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

这篇关于如何微调得到所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆