如何使用AutoCompleteTextView提取String?

时间:2015-04-23 00:51:11

标签: java android android-activity

我知道Stackoverflow中有多个帖子解决了这个问题。但是,出于某种原因,我仍然无法从AutoCompleteTextView中提取字符串。为此,我尝试使用onItemClickListener。我无法确定我哪里出错了。

守则:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    addPurchaseItemName = (AutoCompleteTextView) findViewById(R.id.addPurchaseProductName);

    vivzHelper = new VivzDatabaseAdapter(this);

    String[] autoCompleteName = vivzHelper.getInventoryNameFilterBySupplierName(vivzHelper.getSupplierID(param1));
    ArrayAdapter<String> NameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteName);
    addPurchaseItemName.setThreshold(1);// starts working from first char
    addPurchaseItemName.setAdapter(NameAdapter);

    addPurchaseItemName.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            itemName = String.valueOf(arg0.getItemAtPosition(arg2));
        }
    });

}

我想将提取的字符串的值分配给itemName,该值在活动开始时初始化。有人可以指出我哪里出错了吗?我已经浏览了多种资源。也许,我错过了一些东西。

注意:

此代码已在几天前发布,以解决StackOverFlow中IllegalArgumentException上的问题。既然,这个问题的主题没有更明确地指出这里发布的问题,我认为发布一个新问题是有道理的。因此,我希望,我的问题不会被投票或编辑为重复

更新01:@Deividi Cavarzan在编辑此问题时忘记了以下代码行

ArrayAdapter<String> NameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteName);

更新02:声明itemName

public class AddPurchase extends ActionBarActivity {

AutoCompleteTextView addPurchaseItemName;
String itemName;

2 个答案:

答案 0 :(得分:0)

尝试在itemName回调

上获取addTextChangedListener
addPurchaseItemName.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        itemName = s.toString();
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

答案 1 :(得分:0)

如果您只想从自动完成中获取所选项目字符串,那么

itemName = addPurchaseItemName.getText(); 

甚至更好 -

itemName = addPurchaseItemName.getText().toString().trim();

更新回答

而不是设置onItemClickListener,设置OnItemSelectedListener,这肯定有效。

addPurchaseItemName.setOnSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected (AdapterView<?> parent, View view, int position, long id) {
        //... your stuff
        itemName = addPurchaseItemName.getText().toString().trim();
        Toast.makeText(getApplicationContext(), "selected value - "+itemName, Toast.LENGTH_SHORT);
    }
});