1

I have a Firebase DB which I'm using the push() method to add entries to DB, thus generating the random key as a reference for each entry.

In part of the application I'm using a FirebaseListAdapter to populate some DB entries into a list view. Then I'm implementing setOnItemClickListener on my list. What I want to do here is to return the reference for each entry I click on.

    //Firebase DB setup
    mDatabaseStolen =       FirebaseDatabase.getInstance().getReference().child(testing);

    myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            DatabaseReference itemRef = mDatabaseStolen.getRef();

            Toast toast = Toast.makeText(getActivity().getApplicationContext(), itemRef.getKey(), Toast.LENGTH_SHORT);
            toast.show();

        }
    });

Push being handled here:

 mDatabase.child("testing").push().setValue(newBike);

Firebase data:

"testing" : {  
 "-KTA7xijNrK1SK98rZns" : {     
  "color" : "Rjfu",      
  "frameSize" : 0,         
  "make" : "Ggg",     
  "other" : "Xhfhf",     
  "stolen" : false
},

"-KTABiJuH2-RXwmp0Rcu" : {   
"color" : "Red",     
"frameSize" : 0,      
"make" : "Test ",      
"other" : "No",      
"stolen" : false
}

So when I click on the item in the list, I wish to return the reference KTA7xijNrK1SK98rZns or whatever it may be. In the toast in the first code snippet, all I'm returning is the testing string in each click the parent reference.

Any help appreciated.

peterh
  • 11,875
  • 18
  • 85
  • 108
RoRo88
  • 306
  • 1
  • 4
  • 14

1 Answers1

0

You say you have a FirebaseListAdapter. If that is the case, you can get a reference to a specific item at a position with adapter.getRef().

myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        DatabaseReference itemRef = adapter.getRef(position);

        Toast toast = Toast.makeText(getActivity().getApplicationContext(), itemRef.getKey(), Toast.LENGTH_SHORT);
        toast.show();
    }
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    I am using custom arraylist adapter, what should I do to achieve same as above?? – ASAP Jul 19 '17 at 13:57
  • Hi, I used the above code but I got this error `Variable 'adapter' is accessed from within inner class, needs to be declared final` but when I made adapter final I got the error instead `error: incompatible types: String cannot be converted to DatabaseReference` – phwt Jun 20 '18 at 04:43
  • Good catch, the correct method is [`getRef`](https://github.com/firebase/FirebaseUI-Android/blob/master/database/src/main/java/com/firebase/ui/database/FirebaseListAdapter.java#L95). I updated the code in the answer. – Frank van Puffelen Jun 20 '18 at 14:15