如何使用搜索功能将过滤的项目显示在列表视图中(android)

时间:2013-01-28 09:38:22

标签: java android listview layout widget

我的活动中有一个edittext,搜索按钮和listview,根据edittext框中给出的关键字,所有相关项目都应该显示在listview中,现在我可以在toast中获取那些相关项目,这就是所有相关的项目在吐司中一个接一个地加速,然后变得空洞,但我希望它在listview中显示,我将如何制作它?      这是我的代码

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.example.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.notifyDataSetChanged();
                 }

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

                   }

                   public void afterTextChanged(Editable s) {

                   }
                  });


    // Launching new screen on Selecting Single ListItem
    list.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            HashMap<String, String> map = songsList.get(position);

            Intent in = new Intent(Home.this, Singlemenuitem.class);
            in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
            in.putExtra(KEY_DATE, map.get(KEY_DATE));                         
            in.putExtra(KEY_NAME, map.get(KEY_NAME));
            in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
            in.putExtra(KEY_URL, map.get(KEY_URL));

            startActivity(in);
        }                
    });   

}

2 个答案:

答案 0 :(得分:1)

我替换了以下代码,因此我的搜索功能正常工作:)

searchBox.addTextChangedListener(new TextWatcher() {

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

                   for(int i=0;i<songsList.size();i++)
                   {
                   playerName=songsList.get(i).get("title").toString();
                  System.out.println("player name "+playerName);
                  if(textLength<=playerName.length()){
                  //compare the String in EditText with Names in the ArrayList
                    if(searchString.equalsIgnoreCase(playerName.substring(0,textLength))){
                    searchResults.add(songsList.get(i));
                    System.out.println("the array list is "+songsList.get(i));
                    adapter=new LazyAdapter(Home.this, searchResults);   

                     list.setAdapter(adapter);
                    }

                      }


                   }
                   if(searchResults.isEmpty()){
                       Toast toast= Toast.makeText(getApplicationContext(), 
                                  "No Items Matched", Toast.LENGTH_SHORT);  
                                  toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
                                  toast.show();
                   }
                   adapter.notifyDataSetChanged();
                 }

                 public void beforeTextChanged(CharSequence s, int start, int count,
                     int after) {
                 System.out.println("before changed");

                   }

                   public void afterTextChanged(Editable s) {


                                               System.out.println("after changed");
                   }
                  });

答案 1 :(得分:0)

你让过滤最后变得非常混乱。试试适合我的代码。

首先为列表设置过滤为真,

    listView.setAdapter(adapter);
    listView.setTextFilterEnabled(true);

然后使用编辑文本进行过滤,如下所示,

        editText.addTextChangedListener(new TextWatcher() {

        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {

        }

        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {

        }

        public void afterTextChanged(Editable arg0) {
            MyActivity.this.adapter.getFilter().filter(arg0);

        }
    });

使用此代码并检查其是否有效。