首页 > 解决方案 > 是否可以过滤数组列表中的结果,然后将该列表添加到数组适配器?

问题描述

// 我在 allShops
JsonArrayRequest jsonArrayRequest 中从 db 获取数据;jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener() { @Override public void onResponse(JSONArray response) {

            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject jsonObject = response.getJSONObject(i);
                    //allShops is an arraylist
                    allShops.add(jsonObject.getString("name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            //user enters text in edittext et_search
            et_search.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after)
                {


                }

                @Override
                public void onTextChanged(CharSequence cs, int start, int before, int count)
                {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    //here i am adding arraylist to adapter but want it to happen after filtering the arraylist first based on  users input
                    adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,allShops);
                    (Search.this).adapter.getFilter().filter(s);
                    lv_search.setAdapter(adapter);
                }
            });

标签: android

解决方案


我更新了代码的闲置部分:

@Override
                public void onTextChanged(CharSequence cs, int start, int before, int count)
                {
                    if (cs.length()== 0)
                    {
                        adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,new ArrayList<String>());
                        //(Search.this).adapter.getFilter().filter(cs);
                        lv_search.setAdapter(adapter);
                    }
                    else
                    {
                        List<String> filtered = new ArrayList<String>();
                        for(String x:allShops)
                        {
                            if (x.toLowerCase().contains(cs.toString().toLowerCase()))
                            {
                                filtered.add(x);
                            }
                        }
                        adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,filtered);
                        lv_search.setAdapter(adapter);
                    }
                }

推荐阅读