首页 > 解决方案 > 在按钮单击时过滤 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();
            }
        });
    }
});

Firebase 数据库映像 -

标签: androidfirebasefirebase-realtime-database

解决方案


看起来您在 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.


推荐阅读