For example, to get all host_city values
Something like this should do the trick:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference('Apartmani Dzana');
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
System.out.println(childSnapshot.getKey()); // -K...
System.out.println(childSnapshot.child("ap_code").getValue(String.class));
}
}
#Override
public void onCancelled (DatabaseError databaseError) {
throw databaseError.toException();
}
};
);
It may be useful if you take the Firebase codelab for Android before continuing on your own app. It will teach you basic data access and many more things about using Firebase, in a more step-by-step way.
databaseRef.child('Users').addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
// parse the snapshot to your local model
User user = postSnapshot.getValue(User.class);
// access your desired field
String name = user.getName();
}
}
#Override
public void onCancelled (DatabaseError databaseError) {
}
};
);
Related
I have a problem regarding querying the firebase database using a value and getting the specific node. My schema is shown here:
In my schema 'workLocations' belongs to an 'excavationWorks', and 'excavationWorks' belongs to an 'excavationLists'.
That means that the path to a specific workLocation is excavationLists/excavationWorks/workLocations/(specific workLocation)
The problem that I have is that I want to query the workLocations node by the location value (let's say London) and get the parent node (the red circled key which is the key of the specific workLocation).
I have search and read many posts but I haven't managed to make it work.
My code looks like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("workLocations").orderByChild("location").equalTo("London");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot workLoc : dataSnapshot.getChildren()) {
// do something with the individual "issues"
Log.d(TAG, workLoc.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you
To achieve this, you need to query your database twice like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
DatabaseReference workLocationsRef = reference
.child("excavationLists")
.child("excavationWorks")
.child("workLocations");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String key = ds.getKey();
Query query = workLocationsRef.child(key).orderByChild("location").equalTo("London");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String description = snapshot.child("description").getValue(String.class);
Log.d("description", description);
String partentKey = snapshot.getRef().getParent().getKey();
Log.d("partentKey", partentKey);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
workLocationsRef.addListenerForSingleValueEvent(valueEventListener);
Users is my root node, in that I have various childs created by getting the uid of the user who authenticated. Within these childs (uid) their are various childs like Info, General maintenance, Complaints.
I want to show some of the details like gCity, gProductModel from General maintenance child from all the users (uids). Each uid will have a different values of gCity, etc. Under General Maintenance, I want to retrieve all that data by setting it on an adapter and listview.
I am not able to retrieve it.
Database image
retreive code
When i am trying to retrieve data from the current user by using 'getuid()'(As shown below) ,its working fine . But when i try to retrieve all users data using' getkey()' , it isn't working .
user = FirebaseAuth.getInstance().getCurrentUser();
ref= FirebaseDatabase.getInstance().getReference("Users")
.child(user.getUid())
.child("General Maintenance");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(list_users.size() > 0)
list_users.clear();
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
Generalperson user =
postSnapshot.getValue(Generalperson.class);
list_users.add(user);
}
if(list_users.size() != 0)
{ ListViewAdapter adapter = new
ListViewAdapter(ServicehistoryActivity.this, list_users);
list_data.setAdapter(adapter);}
else
{
list_data.setVisibility(View.INVISIBLE);
k.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Please use this code:
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.getKey();
DatabaseReference userIdRef = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.child("General Maintenence").getChildren()) {
String gCity = ds.child("gCity").getValue(String.class);
String gEmail = ds.child("gEmail").getValue(String.class);
String gPhone = ds.child("gPhone").getValue(String.class);
//and so on
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userIdRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
If you get this error, Listen at /Users failed: DatabaseError: Permission denied is because you are not authorized to the Database, check the Rules Tab in the Realtime database and make this change:
{
"rules": {
".read": true,
".write":true
}
}
Hope it helps.
A simple question:
Referring to my database image, I want to get the values of the children of node "user" in a list in an Activity, i.e. values "a" and "m" should be displayed in the list.
What should I use and how?
Please try this code:
DatabaseReference yourRef = FirebaseDatabase.getInstance().getReference().child("user");
yourRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> usersList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String userName = (String) ds.getKey();
usersList.add(userName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
This is the way in which you'll have in your list, a, m ans so on.
Hope it helps.
You can get the info from the docs here
List<User> allUsers = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("user");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
allUsers.clear();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
allUsers.add(userSnapshot.getValue(User.class));
}
yourRecyclerViewAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Users failed, log a message
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
// ...
}
});
I want to get item in the last node added in firebase database from my Android. You can see on the image below i'm not sure how to get the specific node, because unique key is created by Firebase. How to reference to auto-created node and child inside? Thanks a lot
The last node
Try this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query lastQuery = databaseReference.child("mp").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Handle possible errors.
}
});
Hope this helps!
This might work:
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("mp");
Query query = db.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User val", child.child("message").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: Handle errors.
}
});
I prefer to write and retrieve data through objects.
MyObject is POJO.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
MyObject myObject = data.getValue(MyObject.class);
Log.i(TAG, data.getKey() + " = " + myObject.toString());
}
}
console.log('last messages', messages[messages.length-1]);
I want to get list of all Allowed child from this type of JSON Tree:
databaseRef.child('Users').child('Allowded').addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot) {
//
}
}
#Override
public void onCancelled (DatabaseError databaseError) {
} };);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference userRef = database.getReference("users").child(key).child("Alloweded");
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User userObj = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};userRef.addValueEventListener(postListener);
User is your Model class which have lat, lng, name,no., profileUrl etc
Try this I hope it works fine.
Firebase listeners fire for both the initial data and any changes.
If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.
FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue()); //prints "Do you have data? You'll
love Firebase."
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
databaseRef.child('Users').child('Allowded').addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: 1 " + childDataSnapshot.getKey());
for (DataSnapshot childDataSnapshot2 : childDataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: 2 " + childDataSnapshot2.getKey());
}
}
}
}
#Override
public void onCancelled (DatabaseError databaseError) {
} };);