在listview中搜索数据项

时间:2013-02-07 06:34:05

标签: android listview search adapter

为了搜索listview中已完成编码的数据项,这是逻辑,在arraylist上创建了onTextChangededittext的关键字是与listview进行比较,结果存储在名为arraylist的{​​{1}}中,并使用searchResult将其显示在lazyadapter中,以便能够获得搜索结果listview但是现在我必须告诉惰性适配器按顺序排列toast的项目并在listview中显示,我在很多方面尝试过,但没有任何帮助我得到结果。< / p>

这是我的完整代码listview

lazyadapter

LazyAdapter

public class Home extends ListActivity {
ArrayList<HashMap<String, String>> songsList;
ListView list;
LazyAdapter adapter;
JSONArray posts;    

 //ArrayList thats going to hold the search results
  ArrayList<HashMap<String, String>> searchResults;
  LayoutInflater inflater;
// All static variables
static final String URL = "http://www.abc.com/ads/?json=get_recent_posts";  

 static final String KEY_POSTS = "posts";
 static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final EditText searchBox=(EditText) findViewById(R.id.search);
    final ListView  list=(ListView)findViewById(android.R.id.list);

    //get the LayoutInflater for inflating the customomView
     //this will be used in the custom adapter
     inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);


 final  ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
                final JSONParser jParser = new JSONParser();

                // getting JSON string from URL
                JSONObject json = jParser.getJSONFromUrl(URL);
                try {
                     posts = json.getJSONArray(KEY_POSTS);

        // looping through all song nodes <song>
                for(int i = 0; i < posts.length(); i++){
                    JSONObject c = posts.getJSONObject(i);
                    // Storing each json item in variable
                    String id = c.getString(KEY_ID);
                    String title = c.getString(KEY_TITLE);
                    String date = c.getString(KEY_DATE);
                    String content = c.getString(KEY_CONTENT);
                    // to remove all <P> </p> and <br /> and replace with ""
                     content = content.replace("<br />", "");
                     content = content.replace("<p>", "");
                     content = content.replace("</p>", "");

                    //authornumber is agin  JSON Object
                    JSONObject author = c.getJSONObject(KEY_AUTHOR);
                    String name = author.getString(KEY_NAME);

                    String url = null;
                    String slug = null;
                    try {
                    JSONArray atta = c.getJSONArray("attachments");
                    for(int j = 0; j < atta.length(); j++){
                        JSONObject d = atta.getJSONObject(j);

                        slug = d.getString(KEY_SLUG);

                        JSONObject images = d.getJSONObject(KEY_IMAGES);

                        JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
                        url = thumbnail.getString(KEY_URL);

                    }
                    } catch (Exception e) {
                        e.printStackTrace();

                    }

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

            // adding each child node to HashMap key => value
            map.put(KEY_ID, id);
            map.put(KEY_TITLE, title);
            map.put(KEY_DATE, date);
            map.put(KEY_NAME, name);
            map.put(KEY_CONTENT, content);
            map.put(KEY_SLUG, slug);
            map.put(KEY_URL, url);
            // adding HashList to ArrayList
            songsList.add(map);
                }   
                }catch (JSONException e) {
                    e.printStackTrace();

                    }               

              //searchResults=OriginalValues initially
                searchResults=new ArrayList<HashMap<String, String>>(songsList);

         // Getting adapter by passing json data ArrayList
            adapter=new LazyAdapter(this, songsList);    
             list.setAdapter(adapter);


             searchBox.addTextChangedListener(new TextWatcher() {

                 public void onTextChanged(CharSequence s, int start, int before, int count) {
                       //get the text in the EditText
                       String searchString=searchBox.getText().toString();
                       int textLength=searchString.length();

                              //clear the initial data set
                       searchResults.clear();

                       for(int i=0;i<songsList.size();i++)
                       {
                      String playerName=songsList.get(i).get("title").toString();

                      if(textLength<=playerName.length()){

                      //compare the String in EditText with Names in the ArrayList
                        if(searchString.equalsIgnoreCase(playerName.substring(0,textLength)))
                              Toast.makeText(getApplicationContext(),playerName,1).show();
                        searchResults.add(songsList.get(i));
                      }
                       }

                       adapter=new LazyAdapter(Home.this, searchResults);
                       list.setAdapter(adapter);
                       adapter.notifyDataSetChanged();
                     }

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


                       }

                       public void afterTextChanged(Editable s) {


                       }
                      });
                 }

3 个答案:

答案 0 :(得分:0)

我想你错过了这一行只是在yourActivity.this.adapter.getFilter().filter(cs);添加这一行 这里addTextChangedListener这个

 searchBox.addTextChangedListener(new TextWatcher() {           

        @Override
        public void onTextChanged(CharSequence cs, int start, int count, int after) {
            // your data    

            Home .this.adapter.getFilter().filter(cs);                          
        }   

编辑:改变这样

   public void onTextChanged(CharSequence s, int start, int before, int count) {
                   //get the text in the EditText
                   String searchString=searchBox.getText().toString();
                   int textLength=searchString.length();

                          //clear the initial data set
                   searchResults.clear();

                   for(int i=0;i<songsList.size();i++)
                   {
                  String playerName=songsList.get(i).get("title").toString();

                  if(textLength<=playerName.length()){

                  //compare the String in EditText with Names in the ArrayList
                    if(searchString.equalsIgnoreCase(playerName.substring(0,textLength)))
                          Toast.makeText(getApplicationContext(),playerName,1).show();
                    searchResults.add(songsList.get(i));
                  }
                   }

                   adapter=new LazyAdapter(Home.this, searchResults);
                   list.setAdapter(adapter);
                   adapter.notifyDataSetChanged();

       Home .this.adapter.getFilter().filter(s);    
                 }

答案 1 :(得分:0)

我建议你使用Filter类来搜索/过滤列表中的任何项目。你需要从EditText的onTextChanged()API调用该类,并且过滤联系人的逻辑必须写在过滤器类中。 如,

public void onTextChanged(CharSequence s, int start, int before, int count){   
               //Call filter class
        getFilter().filter(s);

    } 
//getFilter class
 public Filter getFilter() {
                 //put a Null check
        if (null == filter) {
                  //Calling a private filter class, that contains the logic..
            filter  = new FilterList(); 
                }
        return filter; 
    }

private class FilterList extends Filter {
//Here, I was using a pojo to store the attributes of the List Item
        List<DefaultPojo> buffer = new ArrayList<DefaultPojo>();
        @Override
        protected FilterList performFiltering(CharSequence constraint) {

            FilterList results = new FilterList();          

                    if(constraint != null && constraint.toString().length() > 0)
                    {
                       if(List != null){
                        int count = List.size();
                        ArrayList<DefaultPojo> filt = new ArrayList<DefaultPojo>(count);

if(constraint != null && constraint.toString().length() > 0){  
                    //Logic for searching the list
}
                    else{
                        //Load the Parent List....                      
                        buffer = List;

                    }
            //Sorting the obtained List..                   
            Collections.sort(buffer);
            if(buffer!=null && buffer.size()>0){
            results.values = buffer; 
            results.count = buffer.size(); }

            return results;
        }
//Setting the content to the List and Adapter will be done by publishResults() method..
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredList = (List<DefaultPojo>)results.values;
            if(filteredList!=null){     
                ListAdapter = new ListAdapter(Contactlist.this,mFilteredContactDetails);
                List.setAdapter(ListAdapter); 
            }
            else{
                List.setAdapter(null);
                ListAdapter=null;
            }           
        }
    }

答案 2 :(得分:0)

我认为您无需在搜索后重新初始化adapter

你可以这样试试。

准备一个ArrayListtempList&amp;在第一次使用songsList初始化它。然后在初始化时将tempList传递给适配器。在搜索时,将tempListsearchResults&amp;只需致电adapter.notifyDataSetChanged()