单击按钮过滤Firebase数据库将返回单个回收视图listItem

时间:2018-07-29 13:08:24

标签: android firebase firebase-realtime-database

我希望ListView仅显示公司名称等于在“搜索”按钮上单击“在EditText中输入的名称”的数据。

Screenshot OF Edit Text & Search Button

按钮点击事件-

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 Database Image -

1 个答案:

答案 0 :(得分:0)

似乎您在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的类型。