dabadee
dabadee

Reputation: 149

Search in ListView populated with JSON data

My problem is the following: i want to implement a search mechanism into my JSON-data generated ListView, but i don't know what to do in my case.

I've found a lot of examples but i want to implement the simplest solution possible and, especially, an understandable one.

Here's my Pastebin with the Adapter and the MainActivity class.

http://pastebin.com/SSXHXK7m

Can you give me any suggestion? I'm stuck.

Upvotes: 0

Views: 611

Answers (1)

zgc7009
zgc7009

Reputation: 3389

The search functionality would be something like this

public void searchList(String query){
    List<Records> matchedActors = new ArrayList<Records>();
    for(int i = 0; i < adapter.getCount(); i++){
        if(adapter.getItem(i).getAuthor().equals(query)
            matchedActors.add(adapter.getItem(i));
    }

    // See below for what to put here
}

You can then either modify the adapter by creating/calling a method in your adapter class that is something like

public void modifyList(List<Records> actorList){
    this.actorList = actorList;
    notifyDataSetChanged();
}

and call adapter.modifyList(matchedActors) after your search, or by instantiating a new instance of your adapter after your serach via,

adapter = new RecordsAdapter(MainActivity.this, R.layout."your_layout_resource", actorList);
listview.setAdapter(adapter);

EDIT

I didn't notice you were using a Filterable ArrayAdapter :P You can implement the following funcitionality in your adapter.

@Override
public Filter getFilter() {
    Filter filter = new Filter() {


     @Override
     protected void publishResults(CharSequence constraint,FilterResults results) {
         actorList = (List<Records>) results.values;
         notifyDataSetChanged(); 
     }

     @Override
     protected FilterResults performFiltering(CharSequence constraint) {
         FilterResults results = new FilterResults(); 
         List<Records> matchedActors = new ArrayList<Records>();

         //NOTE mOriginalValues will be a class variable we use to keep track of our values
         if (mOriginalValues == null) {
             mOriginalValues = new ArrayList<Records>(actorList); 
         }

         if (constraint == null || constraint.length() == 0) { 
             results.count = mOriginalValues.size();
             results.values = mOriginalValues;
         } 
         else {
             constraint = constraint.toString().toLowerCase();
             List<Records> matchedActors = new ArrayList<Records>();
             for(int i = 0; i < getCount(); i++){
                if(mOriginalValues.getAuthor().toLowerCase().startsWith(constraint)
                    matchedActors.add(getItem(i);
             }

             // set the Filtered result to return
             results.count = matchedActors.size();
             results.values = matchedActors;
         }
         return results;
     }

     return filter;
 }

Upvotes: 1

Related Questions