Reputation: 464
I managed to get data from the Firebase Database and show it in an alphabetical order in my ListView.
Now I want to show the value from my database, if I click on an item in the ListView. As an example in my database it says "BB" as a name and the value is "Bye, bye".
So after an onClick event in the ListView a Toast message should show the value. How can I do this?
Here´s my database:
Upvotes: 2
Views: 1928
Reputation: 464
The sample code 'Peter Haddad' provided in his answer basically works fine... IF you design your database in a better way I did back then.
If you use his code, you get the value of the database entry (so the text on the right side in the console database, but I wanted to get the left one.
I recommend using a structure like in the Firebase Docs about Structuring.
It could look something like this:
Here are two posts about searching and querying those kind of databases:
If you anyways want to do it in the way I tried, it`s possible:
In the sample code from 'Peter Haddad' simply replace dataSnapshot.child(selectedFromList).getValue().toString()
with dataSnapshot.child(selectedFromList).getKey().toString()
.
The key represents the text on the left side of the console database structure.
Upvotes: 1
Reputation: 80924
To show the value after you click on an item:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
final String selectedFromList = (String) list.getItemAtPosition(position);
ref.orderByChild(selectedFromList).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String retrievedValue=dataSnapshot.child(selectedFromList).getValue().toString();
Toast.makeText(activity_name.this, "Value: "+retrievedValue, Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Assuming you have a listview with the following:
Afk
MFG
After clicking on an item, get the item at that postion and use it in a query orderByChild
and retrieve it's value.
Upvotes: 2