filtration alphabetically with ListAdapter using listview in android app

163 Views Asked by At

I am working on an android app. The app binds data using json and ListAdpter in Listview. Now I want to filter that data as per user write letter in searchbox. I tried to do it but due to multiple data is bound in the listview and I dont know how to filter it. Below is my code:

private void getdatalatlog(double latitude, double longitude) {
    // TODO Auto-generated method stub
    //value=5;
    String url = "http://bizzcoder.co.in/php/comments.php?latitude='"+latitude+"'&longitude='"+longitude+"'&value='"+value+"'";
    aq.progress(R.id.progressBar1).ajax(url, JSONObject.class, this,"jsonCallback");

}


public void jsonCallback(String url, JSONObject json, AjaxStatus status) {  


    if (json != null) { 

    List<String> city = new ArrayList<String>();
    mCommentList = new ArrayList<HashMap<String, String>>();

        Gson gson = new GsonBuilder().create();
        try {

            JSONArray jsonResponse = json.getJSONArray("posts");
            city = gson.fromJson(jsonResponse.toString(),List.class);
            for (int i = 0; i < jsonResponse.length(); i++) {
                JSONObject c = jsonResponse.getJSONObject(i);       

                String title = c.getString(TAG_TITLE);
                String content = c.getString(TAG_MESSAGE);
                String username = c.getString(TAG_USERNAME);
                String lat = c.getString(TAG_LATITUDE);
                String log = c.getString(TAG_LONGITUDE);
                String cont = c.getString(TAG_CONTACT);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_TITLE, title);
                map.put(TAG_MESSAGE, content);
                map.put(TAG_USERNAME, username);
                map.put(TAG_LATITUDE, lat);
                map.put(TAG_LONGITUDE, log);
                map.put(TAG_CONTACT, cont);
                    // adding HashList to ArrayList
            mCommentList.add(map);


            }
        } 
        catch (JSONException e) {

            Toast.makeText(aq.getContext(), "Error in parsing JSON", Toast.LENGTH_LONG).show();
        }
        catch (Exception e) {
            Toast.makeText(aq.getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
        }

        ListAdapter adapter = new SimpleAdapter(this, mCommentList,
                R.layout.single_post, new String[] { TAG_TITLE,TAG_USERNAME ,TAG_CONTACT ,TAG_MESSAGE ,TAG_LATITUDE , TAG_LONGITUDE 
                        }, new int[] { R.id.shop_name,R.id.address,R.id.contact,R.id.distance,R.id.latitude,R.id.longitude });


        setListAdapter(adapter);

        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                Shopdetail.this.adapter.getFilter().filter(cs);   
            }

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

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub                          
            }
        });

        ListView lv = getListView();    
        lv.setOnItemClickListener(new OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                Intent intent = new Intent();
                 Bundle b = new Bundle();


                 String name= ((TextView) view.findViewById(R.id.shop_name)).getText().toString()+" , "+((TextView) view.findViewById(R.id.contact)).getText().toString();

                 String lati= ((TextView) view.findViewById(R.id.latitude)).getText().toString();

                 String longi= ((TextView) view.findViewById(R.id.longitude)).getText().toString();

                 b.putString("shop",name);
                 b.putString("lati",lati);
                 b.putString("long",longi);
                intent.setClass(Shopdetail.this, Mapview.class);
                intent.putExtras(b);
                startActivity(intent);
            }
        });
} 
     }

There are multiple details bound in listview like shop name, contact number,address etc. I want to filter it only by the shop name. but I red line below getfilter() method.

1

There are 1 best solutions below

12
On

Actually I did it in this way(EditText was on Toolbar, but it can be where ever you want):

            inputSearch = (EditText) findViewById(R.id.inputSearch);
            inputSearch.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                    // When user changed the Text
                    adapter.getFilter().filter(cs.toString());
                }

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

                }

                @Override
                public void afterTextChanged(Editable arg0) {
                    // TODO Auto-generated method stub
                }
            });

Edit:

To filter custom Base adapter you have to put this in class with your adapter:

    List<Fanfic> fanfics;
    private List<Fanfic>filteredData = null;
    private ItemFilter mFilter = new ItemFilter();

You need 2 Lists - 1st with all data, 2nd with filtered data

In all methods you have to use filteredData(in constructor, getCount, getItem, getItemId), not filtered data you just have fill in constructor.

Here is ItemFilter class:

private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();

            FilterResults results = new FilterResults();

            final List<Fanfic> list = fanfics;

            int count = list.size();
            final ArrayList<Fanfic> nlist = new ArrayList<Fanfic>(count);

            String filterableString ;

            for (int i = 0; i < count; i++) {
                filterableString = list.get(i).getName();
                if (filterableString.toLowerCase().startsWith(filterString)) {
                    nlist.add(list.get(i));
                }
            }

            results.values = nlist;
            results.count = nlist.size();

            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredData = (ArrayList<Fanfic>) results.values;
            notifyDataSetChanged();
        }

    }

And add this method to your adapter:

public Filter getFilter() {
    return mFilter;
}

and last thing, you have to implement Filterable.