我有项目列表,并希望为其实现搜索功能。因此,我有一个带有addTextChangedListener的文本框。
搜索结果正常,但是当我尝试将结果设置为ListView时,新结果会附加到旧结果中。
我正在使用Lazy Adapter。如何清除适配器的旧结果?
以下是代码:
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> searchResults = new ArrayList<HashMap<String, String>>();
searchText = (EditText) findViewById(R.id.searchText);
//Count from the server
int count = dataCount();
for (int i = 0; i < dataCount; i++)
{
HashMap<String, String> map = new HashMap<String, String>();
// adding data to HashMap key => value
map.put(KEY_ID, trackNumber);
map.put(KEY_TITLE, trackTitle);
map.put(KEY_ARTIST, trackArtist);
map.put(KEY_DURATION, trackDuration);
map.put(KEY_THUMB_URL, trackAlbumArt);
// adding HashList to ArrayList
songsList.add(map);
}
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
TextWatcher
nameText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
getSong(s);
}
});
获得结果:
Map getSong(CharSequence s)
{
for (HashMap<String, String> map : songsList)
{
if(map.get(KEY_TITLE).contains(s))
{
Log.e("Map","Son"+map);
HashMap<String, String> map2 = new HashMap<String, String>();
// adding each child node to HashMap key => value
map2.put(KEY_ID, map.get(KEY_ID));
map2.put(KEY_TITLE, map.get(KEY_TITLE));
map2.put(KEY_ARTIST, map.get(KEY_ARTIST));
map2.put(KEY_DURATION, map.get(KEY_DURATION));
map2.put(KEY_THUMB_URL, map.get(KEY_THUMB_URL));
searchResults.add(map2);
}
}
adapter=new LazyAdapter(this, searchResults);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
return Collections.emptyMap();
}
谢谢!
答案 0 :(得分:1)
你不是&#34;清洁&#34;开始之前的旧搜索结果。
添加以下行:
searchResults = new ArrayList<HashMap<String, String>>();
在方法getSong()
的开头(在for循环之前)