【问题标题】:Searching data items in listview在列表视图中搜索数据项
【发布时间】:2013-02-07 06:34:05
【问题描述】:

为了在listview 中搜索数据项,我已经完成了编码,这里是逻辑,创建了arraylist,在onTextChanged 类上,edittext 的关键字与listview 和结果存储在arraylist 称为searchResult 并使用lazyadapter 使其显示在listview 中,能够在toast 中获得搜索结果,但现在我必须告诉惰性适配器安排@ 的项目987654331@ 按顺序显示在listview 中,我尝试了很多方法,但没有任何帮助我得到结果。

这是我的完整代码,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) {


                       }
                      });
                 }

懒惰适配器

public class LazyAdapter extends BaseAdapter {
  TextView title;
private Activity activity;
 // private TextWatcher textWatcher;
   private ArrayList<HashMap<String, String>> data;
   private static LayoutInflater inflater=null;
   public ImageLoader imageLoader; 

   public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
     activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
}


public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.activity_home, null);

    TextView title = (TextView)vi.findViewById(R.id.title); // title
    TextView date = (TextView)vi.findViewById(R.id.date); // artist name
    TextView content = (TextView)vi.findViewById(R.id.content);  // duration
    TextView name = (TextView)vi.findViewById(R.id.name); 
    // duration
    ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

    HashMap<String, String> song = new HashMap<String, String>();
    song = data.get(position);



    // Setting all values in listview
   title.setText(song.get(Home.KEY_TITLE));
    date.setText(song.get(Home.KEY_DATE));
    content.setText(song.get(Home.KEY_CONTENT));
    name.setText(song.get(Home.KEY_NAME));

   imageLoader.DisplayImage(song.get(Home.KEY_URL), thumb_image);
    return vi;
} 
  }                                                             

【问题讨论】:

    标签: android listview search adapter


    【解决方案1】:

    我想你错过了这一行,只需在 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);    
                     }
    

    【讨论】:

    • 如果我添加这一行 Home.this.adapter.getFilter().filter(s),m 在 getFilter() 中出现错误,因为“方法 getFilter() 未定义类型 LazyAdapter”。 @NagarjunaReddy.P
    【解决方案2】:

    我建议您使用过滤器类来搜索/过滤列表中的任何项目。您需要从 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;
                }           
            }
        }
    

    【讨论】:

      【解决方案3】:

      我认为你不需要在搜索后重新初始化你的adapter。

      你可以这样试试。

      再准备一个ArrayList 说tempList & 在第一次用你的songsList 初始化它。然后在初始化时将tempList 传递给你的适配器。在搜索时,使用您的 searchResults 重新初始化 tempList 并调用 adapter.notifyDataSetChanged()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-11
        相关资源
        最近更新 更多