我有一个Firebase数据库,可以在列表视图中显示数据。所有数据都包含在对象中,对象中包含数据。我希望能够将示例“Lars”写入搜索栏,然后它必须更新listview以仅包含那些包含该字符串的对象,如果我从搜索栏中删除所有内容,它应该再次显示所有内容。第一个for循环工作,第二个for循环是我尝试搜索数据。 我的Firebase结构如下所示:
private DatabaseReference mDatabaseReference;
private ListView mUserList;
private SearchView searchModule;
private ArrayList<String> mUsernames = new ArrayList<>();
private ArrayList<String> filteredUsernames = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_existing_customer);
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Buyers");
mUserList = (ListView) findViewById(R.id.UserListView);
searchModule = (SearchView) findViewById(R.id.SearchTab);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mUsernames);
final ArrayAdapter<String> filteredArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, filteredUsernames);
mUserList.setAdapter(arrayAdapter);
mDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Map<String, String> map = (Map<String, String>) childSnapshot.getValue();
Log.v("YourValue,","Map value is:" +map.toString());
Log.d("TAG", "onChildAdded:" + dataSnapshot.getKey());
Buyers buyerList = new Buyers(map);
mUsernames.add(buyerList.getData());
}
CharSequence searchValue = (CharSequence) searchModule;
arrayAdapter.getFilter().filter(searchValue);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
答案 0 :(得分:1)
三件事:
您可以使用侦听器侦听查询的任何更改并应用过滤器
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Map<String, String> map = (Map<String, String>) childSnapshot.getValue();
Buyers buyerList = new Buyers(map);
filteredUsernames.add(buyerList.getData());
}
searchModule.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
filteredArrayAdapter.getFilter().filter(newText);
filteredArrayAdapter.notifyDataSetChanged();
return true;
}
});
这或多或少看起来应该如何。但是,由于过滤器应用于适配器,您可以注意到filteredUserNames和mUsernames是相同的,因此您实际上不需要两个列表。或者,如果您需要过滤器,也可以使用if语句和包含检查手动进行过滤。