Khoem Vichet
Khoem Vichet

Reputation: 331

Get Key from Firebase Database Android

I have firebase data as below. I want to display key in the textview when click on ListView.

enter image description here

I try to get key from discount with below code

private void getKeyValues(){

    databaseReference = FirebaseDatabase.getInstance().getReference().child("promotion").child("discount");

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String key = dataSnapshot.getKey();

            for (DataSnapshot child: dataSnapshot.getChildren()){
                //Object object = child.getKey();
                labelGetKey.setText(child.getKey());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("Read Fail", "Error");
        }
    });
}

It's working but only get the last key and show in the textview. the first key or other key didn't show. here is my code for listview

private void retrieveDataShowListView(){
    // Array List and Adapter for Message ListView;
    final ArrayList<String> arrayList = new ArrayList<>();
    final ArrayAdapter<String> adapter;

    databaseReference = FirebaseDatabase.getInstance().getReference().child("promotion").child("discount");

    adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList);
    listViewPromotion.setAdapter(adapter);
    listViewPromotion.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            String showValue = String.valueOf(parent.getItemAtPosition(position));
            editTextPromotion.setText(showValue);

            // Display Key from Database
            getKeyValues();
        }
    });

    databaseReference.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            String strLocation = dataSnapshot.getValue(String.class);
            arrayList.add(strLocation);
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {}

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            String string = dataSnapshot.getValue(String.class);
            arrayList.remove(string);
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {}

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
}

Can you help me what is the mistake about my code. Thanks!

Upvotes: 0

Views: 6956

Answers (2)

Jay Mungara
Jay Mungara

Reputation: 7148

Ok,there is only one thing you have to do is,

private void getKeyValues(){

databaseReference = FirebaseDatabase.getInstance().getReference().child("promotion").child("discount");

databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String key = dataSnapshot.getKey();
        String dataKeys="";

        for (DataSnapshot child: dataSnapshot.getChildren()){
            //Object object = child.getKey();

            dataKeys=dataKeys+child.getKey() + "";
        }
        labelGetKey.setText(dataKeys);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e("Read Fail", "Error");
    }
});
}

your key just gets override every time in your for loop. so, you have to store your every key of each position in string and append it. So, you will get your final key-values in String dataKeys.

So, to get the String of the selected listview item you can get by the item position like, if position is=2;

So, you can do like this,

        int counter=0;
        for (DataSnapshot child: dataSnapshot.getChildren()){
            //Object object = child.getKey();
            if(counter==position-1){
                dataKeys=child.getKey();
                break;
            }
            counter++;
        }
            labelGetKey.setText(dataKeys);

In this way you can find the key for the selected item by passing list item position. I hope you get it. .....

Upvotes: 1

Goktug Basaran
Goktug Basaran

Reputation: 41

I don't know it this is what you want to accomplish but, you could build a string the innermost for loop where you set the textView.

...
        String s = "";
        for (DataSnapshot child: dataSnapshot.getChildren()){
                    //Object object = child.getKey();
                s = s.concat(child.getKey());
                //s = s.concat(" "); if you want to have a white-space in between keys.         
                //s = s.concat("\n") if you want to have every key on a new line.
                }
        labelGetKey.setText(s);
...

However, this is a really bad approach. You can try to use another ListView in your ListView layout if you want to show each key separately. This approach does NOT allow you to use each key on their own, other than just visualization.

Hope this is helpful.

Upvotes: 0

Related Questions