AutoCompleteTextView建议列表总是延迟一个字符,为什么?

时间:2014-11-25 12:46:32

标签: android arraylist android-arrayadapter autocompletetextview

我很难弄清楚以下问题或错误或其他问题。我有一个AutoCompleteTextView,每次用户输入一个字符时,都会调用一个http请求从外部数据库下载建议。这部分工作正常,阈值是3个字符,所以如果用户输入" ma",下拉列表不显示,然后写" mak"我可以清楚地看到http请求被调用并且在日志" make cake"," make what"等出现。 该问题与AutoCompleteTextView有关,因为下拉列表以某种方式延迟了一个字符。

我第一次写" mal"没有下拉列表显示(外部数据库中有错误,在日志中正确显示),然后我删除文本并写下" pum"," pump"显示在日志中,但是" malter"出现在下拉列表中。然后,如果我写" puml","泵"显示在下拉列表中,该列表应该在之前显示为1个字符。

这是Asynctask - 请注意,请求工作正常,正如我之前提到的,日志提出了正确的建议,设置适配器等可能存在问题(我猜......)。

SuggestAsyncTask:

 private class SuggestAsyncTask extends AsyncTask<String, Void, ArrayList<String>> {

          @Override
          protected void onPostExecute(ArrayList<String> result) {
              //Logging the elements of array_goals_name is also OK.             
              adapter = new ArrayAdapter<String>(NewGoalsActivity.this, android.R.layout.simple_list_item_1, array_goals_name);
              actv_name.setAdapter(adapter);

          }

          @Override
          protected void onPreExecute() { }

          @Override
          protected ArrayList<String> doInBackground(String... params) {

              try{
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = null;
                    httppost = new HttpPost(search_goal);

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                    nameValuePairs.add(new BasicNameValuePair("newtext", params[0]));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    }catch(Exception e){
                            Log.e("error", "Error in http connection "+e.toString());
                    }
                    //convert response to string
                    try{
                            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                            StringBuilder sb = new StringBuilder();
                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                    sb.append(line + "\n");
                            }
                            is.close();
                            //Log.i("sb", sb + "");
                            Bresult=sb.toString();
                            //Log.i("Bresult", Bresult + "");
                    }catch(Exception e){
                            Log.e("error", "Error converting result "+e.toString());
                    }

                    array_goals_name.clear();

                    try {
                        if (Bresult != null) {
                            jArray = new JSONArray(Bresult);
                            for(int i=0;i<jArray.length();i++){
                                JSONArray innerJsonArray = jArray.getJSONArray(i);
                                for(int j=0;j<innerJsonArray.length();j++){  
                                    JSONObject jsonObject = innerJsonArray.getJSONObject(j);
                                    array_goals_name.add(jsonObject.getString("NAME"));
                                    Log.d("NAME: ", "" + jsonObject.getString("NAME")));  
           //this works fine! When the 3rd character is pushed the log output is correct, etc

                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                return null;

          }

      }

你可以看到在onPostExecute()中我总是在array_goals_name ArrayList之后设置新的适配器,我希望它显示在ArrayList中包含的建议。我没有在这里包含,但是记录这个ArrayList array_goals_name的元素也没问题(得到正确的建议,但没有下拉列表)。

OnCreate的一部分:

array_goals_name = new ArrayList<String>();
actv_name = (NewBucketCustomAutoCompleteTextView) findViewById(R.id.actv_name);
adapter = new ArrayAdapter<String>(NewBucketActivity.this, android.R.layout.simple_list_item_1, array_goals_name);
actv_name.setWillNotCacheDrawing(true);

actv_name.addTextChangedListener(new TextWatcher() {

              @Override
              public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (actv_name.isPerformingCompletion()) {
                        // An item has been selected from the list. Ignore.
                        return;
                   } else {
                       if (actv_name.getText().toString().length() > 2) {
                            new SuggestAsyncTask().execute(actv_name.getText().toString());
                            }
                   }           
              }

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

            @Override
            public void afterTextChanged(Editable s) {  }

          });

我还创建了NewBucketCustomAutoCompleteTextView类来制作自定义AutoCompleteTextView,如果有任何问题过滤(忽略)空格键的话。这部分代码是一个方案。 的 NewBucketCustomAutoCompleteTextView:

public class NewBucketCustomAutoCompleteTextView extends AutoCompleteTextView {

   public NewBucketCustomAutoCompleteTextView(Context context) {
       super(context);
       // TODO Auto-generated constructor stub
   }

   public NewBucketCustomAutoCompleteTextView(Context context, AttributeSet attrs) {
       super(context, attrs);
       // TODO Auto-generated constructor stub
   }

   public NewBucketCustomAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) {
       super(context, attrs, defStyle);
       // TODO Auto-generated constructor stub
   }

   // this is how to disable AutoCompleteTextView filter
   @Override
   protected void performFiltering(final CharSequence text, final int keyCode) {
       String filterText = "";
       super.performFiltering(filterText, keyCode);
   }
}

可能是什么问题?

---------编辑-----------------

    actv_name = (NewBucketCustomAutoCompleteTextView) findViewById(R.id.actv_name);
    actv_name.setThreshold(3);
    String[] from = { "name" };
    int[] to = { android.R.id.text1 };
    actv_name.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.otf"));
    SimpleCursorAdapter a = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
    a.setStringConversionColumn(1);

        FilterQueryProvider provider = new FilterQueryProvider() {
            @Override
            public Cursor runQuery(CharSequence constraint) {
                // run in the background thread
                Log.d("TAG", "runQuery constraint: " + constraint);
                if (constraint == null) {
                    return null;
                }


                try {

                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = null;
                    httppost = new HttpPost(search_goal);

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                    nameValuePairs.add(new BasicNameValuePair("newtext", constraint.toString()));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    }catch(Exception e){
                            Log.e("error", "Error in http connection "+e.toString());
                    }
                    //convert response to string
                    try{
                            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                            StringBuilder sb = new StringBuilder();
                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                    sb.append(line + "\n");
                            }
                            is.close();
                            //Log.i("sb", sb + "");
                            Bresult=sb.toString();
                            //Log.i("Bresult", Bresult + "");
                    }catch(Exception e){
                            Log.e("error", "Error converting result "+e.toString());
                    }

                    String[] columnNames = { "_id" , "name" };
                MatrixCursor c = new MatrixCursor(columnNames);

                    try {
                        if (Bresult != null) {
                            jArray = new JSONArray(Bresult);
                            for(int i=0;i<jArray.length();i++){
                                JSONArray innerJsonArray = jArray.getJSONArray(i);
                                for(int j=0;j<innerJsonArray.length();j++){  
                                    JSONObject jsonObject = innerJsonArray.getJSONObject(j);
                                    array_goals_name.add(jsonObject.getString("NAME"));
                                    Log.d("NAME", "" + jsonObject.getString("NAME"));
                                    c.newRow().add(j).add(jsonObject.getString("NAME"));
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                return c;
            }
        };
        a.setFilterQueryProvider(provider);
        actv_name.setAdapter(a);

0 个答案:

没有答案