//database
database = FirebaseDatabase.getInstance();
foods = database.getReference("Food/" + categoryID);
I need categoryID. How can I retrieve it?
To get the id, try the following:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Food");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The snapshot is at child Food then you can iterate inside the direct child and get the id which is 01
I have found a solution. like this;
categoryID = getIntent().getStringExtra("CategoryID");
foodId = getIntent().getStringExtra("FoodId");
database = FirebaseDataBase.getInstance();
foods = database.getReference("Food/" + categoryID + "/" + foodId);
with this method I could reach both food and category ID.
Related
I am trying to retrive messages from Message node. Each message in messages has an Id. The final result I am trying to achieve is just the message for each user or is there ant better way to store the data as I don't need the key for storing messages, but when I don't include the key the old data gets deleted.
structure of my data
DatabaseReference dbfriends= FirebaseDatabase.getInstance().getReference().child("Users");
dbfriends.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
for (DataSnapshot productSnapshot:dataSnapshot.getChildren())
{
Log.i("IDDD",productSnapshot.toString());
Log.i("IDDDDDDDD",productSnapshot.child("Messages").getValue().toString());
String friend=productSnapshot.child("Username").getValue().toString();
Log.i("This is friend",friend.toString());
friends.add(friend);
}
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = rootRef.child("Users").child(uid).child("Messages");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String sender = ds.child("sender").getValue(String.class);
String message = ds.child("message").getValue(String.class);
Log.d(TAG, sender + ": " + message);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
messagesRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be:
Jeffy: Alic how r you?
Jeffy: Alic how r you?
If you also need the key, simply use:
String key = ds.getKey();
So please look at the problem iam facing.
Assuming that the SuccessfulOrders node is a direct child of your Firebase database root, to get that data and add it into a list, please use the following code:
String phoneNo = FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference phoneNoRef = rootRef.child("SuccessfulOrders").child(phoneNo);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ListView<String> list = new ArrayList<>();
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String productName = ds.child("productName").getValue(String.class);
list.add(productName);
Log.d("TAG", productName);
}
//Do what you need to do with your list.
Log.d("TAG", list.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNoRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logat wil be:
1000 Website Visit
SOCIAL MEDIA PACK
//and so on
My Database struckture
This is my database in Firebase and I'm developing an Android application. Now I want to retrieve all the data from "Generated" node where my current user's userid matches the "userId" in data.
I want to know the query in Firebase to fetch that particular data.
Firebase Query firebase query
Read the Firebase Realtime Database Documentation to get some idea firebase realtime database
To Get Current User Uid
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = user.getUid(); // user.getUid() will return null if you are not log in
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query query = db.child("Leads").child("Generated").orderByChild("userid").equalTo(current_uid);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// do something
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or Try This One
db.child("Leads").child("Generated").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot ds: dataSnapshot.getChildren())
{
SomeClass someClass = ds.getValue(SomeClass.class);
if(someClass.getUid().equals("uid")){
// i don't if it is the best practice or not but you can do with this as well
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To access every item from that reference you will need something like this:
mDatabase.child("Leads").child("Generated").child(uid).addValueEventListener(new ValueEventListener() {
final List<String> lstItems= new ArrayList<String>();
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = (String) ds.getKey();
String values = (String) ds.getValue();
Log.e("Values",""+values );
lstItems.add(values );
}
PS: you can remove .child(uid) in your reference if you want to get all the children of Generated (it's going to be all the uids).
I am developing app to display user score that store in firebase database but after running application it won't display data in listview
below is my code:-
listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);
reference = FirebaseDatabase.getInstance().getReference("score");
leaderBoards = new ArrayList<>();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
leaderBoards.add(0,leaderBoard);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Collections.sort(leaderBoards);
CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
listViewLeaderBoard.setAdapter(adapter);
adapter.notifyDataSetChanged();
Database snapshot:-
Output:-
try this:
listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);
reference = FirebaseDatabase.getInstance().getReference("score");
leaderBoards = new ArrayList<>();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
leaderBoards.add(leaderBoard);
CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
listViewLeaderBoard.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To solve this, move this line of code:
List<LeaderBoard> leaderBoards = new ArrayList<>();
inside onDataChange() method, otherwise it will always be, due the asynchronous behaviour of this method which is called even before you are trying to add those objects of LeaderBoard class to the list.
Also, leaderBoards.clear(); is no needed anymore. Your code should look something like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String imageUrl = ds.child("imageUrl").getValue(String.class);
String name = ds.child("name").getValue(String.class);
long score = ds.child("score").getValue(Long.class);
Log.d("TAG", image + " / " + Urlname + " / " + score);
list.add(image + " / " + Urlname + " / " + score);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
You can find and change the rules for your database in the Firebase console.Simply choose your project, click on the Database section on the left, and then select the Rules tab.I don't know you have done this or not try this hope this will help you.
{
"rules": {
".read": true,
".write": true
}
}
I have stored some List of person objects on Firebase.I want to retrieve this full List into newList of person from database.The class perosn contains another List batch
My class person look like:
public class person {
public String name,sid;
public HashMap<String,String> batch;
public int cls;
}
The code I have used is:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference fDatabaseRoot = database.getReference("studentsList");
fDatabaseRoot.orderByChild("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot areaSnapshot : dataSnapshot.getChildren()) {
Map<String,person> td =
(HashMap<String,person>)areaSnapshot.getValue();
// arrayListStudent= (List<person>) td.values();
// Log.d("aaa1",arrayListStudent.toString());
}
//Log.d("aaa",arrayListStudent.toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Where am i getting wrong.Please give some hint and suggestions....
Here is the screenshot of my database structure:
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studentsListRef = rootRef.child("studentsList");
Query query = studentsListRef.orderByChild("name");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String key1 = ds.child("batch").child("0").getValue(String.class);
String key2 = ds.child("batch").child("1").getValue(String.class);
Log.d("TAG", name + " / " + key1 + " / " + key2);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
In this way, you'll get the value of name and of both fields under batch.