来自json的Android过滤器listview数据

时间:2014-01-25 14:10:24

标签: android json listview

我想从json过滤listview数据。这是我到目前为止所尝试的:

  wsSearch = (EditText) findViewById (R.id.wsSearch);
    listview = (ListView) findViewById(R.id.list_view);
    listview.setTextFilterEnabled(true);
    wsSearch.addTextChangedListener(new TextWatcher (){

        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }

        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence cs, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub
            //BAPTISMAL_SONG.this.adapter2.getFilter().filter(cs); 

            ArrayList<HashMap<String, String>> arrayTemplist= new ArrayList<HashMap<String,String>>();
            String searchString = cs.toString();//wsSearch.getText().toString();
            for (int i = 0; i < arraylist.size(); i++)
            {
                String currentString = arraylist.get(i).get(BAPTISMAL_SONG.TAG_TITLE);
                if (searchString.equalsIgnoreCase(currentString))
                {
                    arrayTemplist.add(arraylist.get(i));
                }
            }
            adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arraylist);
            listview.setAdapter(adapter2);

        }

    });

我遵循了这个answer但是当我尝试在我的edittext上输入内容时,它不会过滤。我在这里做错了什么?非常感谢你的帮助。感谢。

1 个答案:

答案 0 :(得分:2)

替换

adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arraylist);
listview.setAdapter(adapter2);

使用:

adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arrayTemplist);
listview.setAdapter(adapter2);

在您的onTextChanged方法中。现在就是你正在执行过滤器的方式,但是你使用的是旧集合,而不是放置过滤内容的集合。

编辑:如果字符串的长度至少为2,要执行过滤,那么您可以这样做:

public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
    // TODO Auto-generated method stub
    //BAPTISMAL_SONG.this.adapter2.getFilter().filter(cs); 
    String searchString = cs.toString();//wsSearch.getText().toString();
    if(searchString.length() != 2) {
        adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arraylist);
        listview.setAdapter(adapter2);
        return;
    }
    ArrayList<HashMap<String, String>> arrayTemplist= new ArrayList<HashMap<String,String>>();
    for (int i = 0; i < arraylist.size(); i++)
        {
        String currentString = arraylist.get(i).get(BAPTISMAL_SONG.TAG_TITLE);
        if (searchString.equalsIgnoreCase(currentString))
            {
                arrayTemplist.add(arraylist.get(i));
            }
        }
    adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arrayTemplist);
    listview.setAdapter(adapter2);
}