android - 在按钮单击时过滤 Firebase 数据库返回单个回收视图列表项
问题描述
我希望 ListView 仅显示公司名称等于在 Search Button Click 上的 EditText 中输入的数据:
按钮点击事件 -
Button btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText objCompany = (EditText) findViewById(R.id.filterEdit);
mMessagesDatabaseReference.orderByChild("company").equalTo(objCompany.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot d1 : dataSnapshot.getChildren()) {
for(DataSnapshot d2 : d1.child("company").getChildren()) {
postAdapterObject.clear();
// Get the value from the DataSnapshot and add it to the item list
post itemObject = d1.getValue(post.class);
//this is where data from database is entered into a list of objects
postAdapterObject.add(itemObject);
postAdapterObject.notifyDataSetChanged();
}
}
Toast.makeText(MainActivity.this, "Data Filtered", Toast.LENGTH_LONG).show();
}
else{
postAdapterObject.clear();
postAdapterObject.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Data Not Found!", Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
postAdapterObject.clear();
postAdapterObject.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "No Data Found! Try with some other data entry", Toast.LENGTH_LONG).show();
}
});
}
});
解决方案
看起来您在 JSON 中循环的级别太深了。这要简单得多,并且应该接近您的需要:
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
postAdapterObject.clear();
for(DataSnapshot d1: dataSnapshot.getChildren()) {
post itemObject = d1.getValue(post.class);
postAdapterObject.add(itemObject);
}
postAdapterObject.notifyDataSetChanged();
if (postAdapterObject.size() > 0) { // TODO: write this condition
Toast.makeText(MainActivity.this, "Data Filtered", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data Not Found!", Toast.LENGTH_LONG).show();
}
}
您可能需要修复签入if (postAdapterObject.size() > 0) {
,因为它取决于postAdapterObject
.
推荐阅读
- django - 多租户应用程序如何适应基于微服务的架构?
- c# - 带有 Naudio 和 TCP 流的断断续续的音频。缓冲区满异常
- swift - 尤里卡表单:输入然后格式化为 AttributedString
- excel - 如果 x=a1,则 y=b1 如果 x=a2,则 y=b2
- visual-studio-code - Vscode API - 自定义视图容器图标
- excel - VBA - Evaluate(Replace(..)) 因特定输入而出错
- c# - Xamarin.Mac 打印功能只打印屏幕,而不是整个表格
- sql-server - 将字段转换为浮点数,但除以整数会产生不正确的结果
- jenkins - 如何将 SonarQube Quality Gate 集成到我的 Jenkins 管道中?
- angular - NgRx 通过 dispatch 方法传递有效载荷来更新存储