知道已知值的键/子名称

时间:2017-07-10 08:34:48

标签: android firebase firebase-realtime-database

假设我知道孩子的特定价值。如何使用我知道的值获取孩子的名字。

private void couponsearch() {
        final EditText taskEditText = new EditText(this);
        AlertDialog.Builder dialog = new AlertDialog.Builder(this)
                .setTitle("My Akiba")
                .setMessage("Enter Akiba Code Here.")
                .setView(taskEditText);
        dialog.show();

        taskEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (taskEditText.getText().length() == 6) {
                    String string = taskEditText.getText().toString();
                    DatabaseReference dref =FirebaseDatabase.getInstance().getReference();

                    dref.child("codes")
                            .equalTo(string)
                            .addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                    for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
                                        String clubkey = childSnapshot.getKey();
                                        code.setText(clubkey);
                                        System.out.println(clubkey);
                                    }
                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {

                                }
                            });
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

例如,我键入了 HUIYUI 值,我想要一个查询是否存在的搜索,如果是,我想返回的孩子的名字AA 20 MG

码  -AA 20 MG  代码: “HUIYUI”

任何帮助都将受到高度赞赏。

JSON结构:

{
    "Cocacola 300ml": {
        "code": "CCCCCC",
        "value": 20
    },
    "Milk big": {
        "code": "IUDKH",
        "value": 20
    },
    "TUZO Milk": {
        "code": "TZOMLK",
        "value": 20
    },
    "Unga Jogoo 50kgs": {
        "code": "UNKREW",
        "value": 50
    }
}

1 个答案:

答案 0 :(得分:0)

您需要具体说明您要订购的字段:

DatabaseReference childRef = dref
    .child("codes")
    .orderByChild("code")
    .equalTo(string)
childRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            System.out.println(childSnapshot.getKey());
            System.out.println(childSnapshot.getChild("value").getValue());
        }
    }
    ...