AutoCompleteTextView 在从数据库添加数据时无法正常工作

AutoCompleteTextView Not Working Properly on adding data from Database

我有一个 AutoCompleteTextView,当我像这样静态定义我的字符串时它工作正常..

private String Names[] = {"Hassan", "Usman", "Kristen Stewart"};

那我就这样做..

  ArrayAdapter<String> adapter = new ArrayAdapter<String>
            (this, android.R.layout.select_dialog_item, Names);
    //Getting the instance of AutoCompleteTextView

    catgNames.setThreshold(0);//will start working from 0 character
    catgNames.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView

但是 当我尝试从 Sqlite 加载一些数据时,下拉 建议不起作用。我正在做这样的事情..

  Categories = new String[100]
  int i =0;
  DatabaseHandler db = new DatabaseHandler(this);
    List<entries> entries1 = db.getCategories();
    for (entries cn : entries1) {
        Log.i("", cn.getCategories());

        Names[i] = cn.getCategories();
        i++;
    }

然后我定义适配器..

    ArrayAdapter<String> adapter = new ArrayAdapter<String>
            (this, android.R.layout.select_dialog_item, Names);
    //Getting the instance of AutoCompleteTextView

    catgNames.setThreshold(0);//will start working from 0 character
    catgNames.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView

这行不通。 log-cat 中没有错误或警告..

试试这个:

String[] Categories =[entries1.size];


int i =0;
  DatabaseHandler db = new DatabaseHandler(this);
    List<entries> entries1 = db.getCategories();
    for (entries cn : entries1) {
        Log.i("", cn.getCategories());

    Categories[i] = cn.getCategories();
    i++;
}

更改您的阈值:

catgNames.setThreshold(0);

像这样。

catgNames.setThreshold(1);

希望有用。

我想知道为什么在将值添加到 Names[] 时要在 ArrayAdapter 中传递类别?它应该是 'Names' 而不是你的 ArrayAdapter 中的 'Categories',就像

ArrayAdapter<String> adapter = new ArrayAdapter<String>
        (this, android.R.layout.select_dialog_item, Names);

或者您可以创建一个列表,添加所有数据库列值并将它们传递到您的 ArrayAdapter。希望对您有所帮助!

我已经解决了这个问题..

这是我犯的错误..

Categories = new String[100]

这将创建一个大小为 100 的数组,我没有完全使用它。

现在..

DatabaseHandler db = new DatabaseHandler(this);
List<entries> entries1 = db.getCategories();
for (entries cn : entries1) {
    Log.i("", cn.getCategories());

    Names[i] = cn.getCategories();
    i++;
}

此代码仅将数据库中的值放入,其余值在名称数组中仍然为空。

由于此自动完成文本视图无法正常工作..

我是这样解决的..

int i=0;
    DatabaseHandler db = new DatabaseHandler(this);
    List<entries> entries1 = db.getCategories();
    for (entries cn : entries1) {
        i++;
    }
    Names = new String[i];
    int j=0;
    List<entries> entries3 = db.getCategories();
    for (entries cn : entries3) {
        Names[j] = cn.getCategories();
        j++;
    }

从这个link

找到解决方案