问题
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.
回答1:
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();
}
});
来源:https://stackoverflow.com/questions/39848072/retrieving-the-firebase-key-from-onitemclick-in-firebaselistadapter