Android:onItemClick方法中的AutoCompleteTextView适配器为空

时间:2011-08-03 14:35:59

标签: android autocompletetextview

正如标题所示,我有一个AutoCompleteTextView,我在onTextChanged方法中填充。我有一个扩展ArrayAdapter的自定义数组。我已将onItemClickListener添加到AutoCompleteTextView,并且在onItemClick方法中,如果我执行“parent.getAdapter()。getItem(position) - 它会抛出错误,因为项目未在适配器中填充。

提供相关代码:

public void onCreate(Bundle icicle){
    super.onCreate(icicle);
    thisContext = this;
    setContentView(R.layout.redeemareavouchers);

    // SUBURB SEARCH (AUTOCOMPLETE)
    txtSuburbSearch = (AutoCompleteTextView) findViewById(R.id.txtSearchSuburb);
    txtSuburbSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try{
                //getSuburbSearch returns results from backend
                PostalCodeDTO[] suburbs = client.getSuburbSearch(txtSuburbSearch.getText().toString(), 5);
                txtSuburbSearch.setAdapter(new SuburbAdapter(thisContext, R.layout.suburbitem, Arrays.asList(suburbs)));
            } catch (IOException ioe){ }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        @Override
        public void afterTextChanged(Editable s) { }
    });

    txtSuburbSearch.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            try{
                Object test =parent.getAdapter().getItem(position);
                if (((SuburbAdapter)parent.getAdapter()).getItem(position) != null){
                    //I NEED TO GET HERE!!:)
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    });
}

和我的SuburbAdapter:

public class SuburbAdapter extends ArrayAdapter<PostalCodeDTO>{
    private final List<PostalCodeDTO> items;

    public SuburbAdapter(Context context, int textViewResourceId, List<PostalCodeDTO> items){
        super(context, textViewResourceId, items);
        this.items = items;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        View v = convertView;
        if (v == null){
            LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.suburbitem, null);
        }

        PostalCodeDTO suburbs = items.get(position);
        if (suburbs != null){
            TextView sub = (TextView) v.findViewById(R.id.itemSuburb);

            if (sub != null){
                sub.setText(suburbs.toString());
            }
        }

        return v;
    }

    @Override
    public PostalCodeDTO getItem(int position){
        return items.get(position);
    }
}

0 个答案:

没有答案