Android Studio - Spinner - 获取Spinner项不起作用

时间:2017-08-23 11:37:13

标签: java android spinner

我尝试了几个小时从我的Spinner-Object中获取该项目,但我总是从Spinner数组中获取第一项。 该数组在string.xml中定义。 这个错误是由不同的背景引起的吗? 当我只使用getSelectedItem命令时,我得到一个NullPointer参考

 String taskName;
 String taskTag;
 Spinner spinner;
 ArrayAdapter<CharSequence> adapter;


 public void newTaskName() {

    final AlertDialog.Builder taskBuilder = new AlertDialog.Builder( MainActivity.this );
    final View bView = getLayoutInflater().inflate( R.layout.dialog_taskname, null );
    final EditText bTaskName = (EditText) bView.findViewById( R.id.taskNameEditText );
    Button buttonAdd = (Button) bView.findViewById( R.id.buttonAdd );
    Button buttonBack = (Button) bView.findViewById( R.id.buttonBack );


    taskBuilder.setView( bView );
    final AlertDialog dialog = taskBuilder.create();
    dialog.show();

    buttonAdd.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!bTaskName.getText().toString().isEmpty()) {

                taskName = bTaskName.getText().toString();
                taskTag = (String) spinner.getSelectedItem();
                dialog.dismiss();
                System.out.println("Das ist der Tag: "+ taskTag);
                newTask( taskName, taskTag );

            } else {
              (...)

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.dialog_taskname );

    spinner = (Spinner) findViewById( R.id.spinner_WT );
    adapter = ArrayAdapter.createFromResource( this, R.array.array_wochentage, android.R.layout.simple_spinner_item );
    adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
    spinner.setAdapter( adapter );

    spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Object item = spinner.getItemAtPosition(position);

        }

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



            setContentView( R.layout.activity_main );
                    (...)

1 个答案:

答案 0 :(得分:0)

而不是这一行:

Object item = spinner.getItemAtPosition(position);

尝试使用这个:

Object item = parent.getItemAtPosition(position)

另外,您是否在代码中添加了以下行?

 Spinner spinner = (Spinner) findViewById(R.id.spinner);
 spinner.setOnItemSelectedListener(this);