I'm using Firebase for an Android project and it works well while pushing the data to a server, but when retrieving the data, I get nothing.
here is the structure for my firebase
and here is my code for retrieving the data form Firebase
mRef.child("User").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
counter = dataSnapshot.getChildrenCount();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
post = postSnapshot.getValue(SettersGetters.class);
nicuNames.add(post.getNicuName());
nicuAddresses.add(post.getNicuAddress());
niucCount.add(post.getNicuCount());
nicuPrices.add(post.getNicuCount());
nicuPhones.add(post.getNicuPhone());
nicuUpdate.add(post.getNicuUpdate());
nicuLat.add(post.getNicuLat());
nicuLng.add(post.getNicuLng());
nicuDes.add(post.getNicuDesc());
a++;
Toast.makeText(MapsActivity.this,"jhkjhk", Toast.LENGTH_LONG).show();
System.out.println(nicuNames.get(0));
}
//Toast.makeText(MapsActivity.this,"jhkjhk" + a, Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
While making a Toast to print at least the number of Children, it returns 0 every time
Toast.makeText(MapsActivity.this,a+"",Toast.LENGTH_SHORT).show();
You want to listen to children events of User key, not value events.
Replace
mRef.child("User").addValueEventListener(new ValueEventListener() {
With
mRef.child("User").addChildEventListener(new ChildEventListener() {
Then, implement
onChildAdded(DataSnapshot snapshot, String previousChildName)
onChildChanged(DataSnapshot snapshot, String previousChildName)
And from there, you map a DataSnapshot to a (preferrably better named class than) SettersGetters.class
try this
mRef.child("User").child("Kfx7408plvgugiMR1Se").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
counter = dataSnapshot.getChildrenCount();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
post = postSnapshot.getValue(SettersGetters.class);
nicuNames.add(post.getNicuName());
nicuAddresses.add(post.getNicuAddress());
niucCount.add(post.getNicuCount());
nicuPrices.add(post.getNicuCount());
nicuPhones.add(post.getNicuPhone());
nicuUpdate.add(post.getNicuUpdate());
nicuLat.add(post.getNicuLat());
nicuLng.add(post.getNicuLng());
nicuDes.add(post.getNicuDesc());
a++;
Toast.makeText(MapsActivity.this,"jhkjhk", Toast.LENGTH_LONG).show();
System.out.println(nicuNames.get(0));
}
//Toast.makeText(MapsActivity.this,"jhkjhk" + a, Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
I am trying to read data from firebase in my android app. This is how it looks.
I want to read the marked data. I am able to read the key of categories child. But unable to read the ids values.
Here's my code:
dbCategories = FirebaseDatabase.getInstance().getReference("categories");
dbCategories.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for (DataSnapshot ds: dataSnapshot.getChildren()){
String name = ds.getKey();
String ids = ds.child("ids").getValue(String.class);
Log.i(name, "onDataChange: "+ids);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
You could not connect to the root you want. For example, tcat2, you can modify the ids.
You must specify the path from which you want to read.
You can try this :
dbCategories = FirebaseDatabase.getInstance().getReference("categories");
dbCategories.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for (DataSnapshot ds: dataSnapshot.getChildren()){
String name = ds.getKey();
for(DataSnapshot ds1 : ds.child(name).child("ids").getChildren()){
String ids = ds1.getValue(String.class);
Log.i(name, "onDataChange: "+ids);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I hope I helped you.
I have a questions how could i push array list to my freebase data base
and also read it to add a new element , then push it again.
In the above photo you can see i have added array list joinedStudents
and i need to read it and push new elements to it
I've tried the following
DatabaseReference requestsRef = FirebaseDatabase.getInstance().getReference();
requestsRef.child("requests").child(requestID).child("joinedStudents");
requestsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d : dataSnapshot.getChildren()) {
String jR = d.getValue(String.class);
joinedStudents.add(jR);
}
joinedStudents.add(studentID);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, "error fetching data from firebase");
}
});
for (String string : joinedStudents) {
requestsRef.child("requests").child(requestID).child("joinedStudents").setValue(string);
}
but it's not working
I believe you have your references slightly mixed up. Try something like:
DatabaseReference joinedStudentsRef = FirebaseDatabase.getInstance().getReference().child("requests").child(requestID).child("joinedStudents");
joinedStudentsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d : dataSnapshot.getChildren()) {
String jR = d.getValue(String.class);
joinedStudents.add(jR);
}
joinedStudents.add(studentID);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, "error fetching data from firebase");
}
});
for (String string : joinedStudents) {
joinedStudentsRef.child("1").setValue(string); // setValue is for key, value
// but you have an array
}
Where your reference is now the direct node that you want to monitor/read/write
I have an android application which does the following:
com.google.firebase.database.Query query = mUsersRef
.orderByChild(USER_TABLE_EMAIL)
.startAt(searchTerm)
.endAt(searchTerm + FirebaseConstants.SEARCH_ESCAPE);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot d = dataSnapshot;
getView().showSearchResults();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: something?
}
});
I was wondering what the simplest way to convert dataSnapshot into User objects was. Do I need to get returned json and do some form of conversion? or is there a better way?
You can convert your data snapshot into an object as shown below:
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapShot : dataSnapshot.getChildren()){
User user = snapShot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: something?
}
});
I want to get particular value using from DataSnapshot.
I am attaching the screenshot here so kindly check and help me to get particular value from Realtime Database.
Actually I am implementing chat application in which I want to get value of user from group_list.
Here is my code.
private void loadTotalGroupList() {
referenceMainUrl = FirebaseDatabase.getInstance().getReferenceFromUrl("https://pure-coda-174710.firebaseio.com");
referenceGroupList = referenceMainUrl.child("group_list");
//Check if child is available or not.
referenceGroupList.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.e("dataSnapshot"," ==>"+dataSnapshot);
Map<String, Object> newPost = (Map<String, Object>) dataSnapshot.getValue();
Log.e("newPost"," ==>"+newPost);
Log.e("user: ","==>" + newPost.get("user")); // Here I am getting null value
} else {
Log.e("Child not found", " >>>");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
and log showing like this. DataSnapshot { key = group_list, value = {First Group={-KtBH9gnTszNxcXjNu9A={message=assaasas, user=sakib}}} }
I have resolved my issue by using addChildEventListener
referenceGroupList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
Log.e("dataSnapshot KEY", " ==>" + dataSnapshot.getKey());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here dataSnapshot.getKey() returns all sub child of it.
You're listening to the location /group_list in your code. That means a a snapshot from that location will contain the following:
/First Group
/-KtBH9gnTszNxcXjNu9A
message = "..."
user = "..."
If you want to get the user value from that location, you'll have to dig into it using each intermediate path:
dataSnapshot.child("First Group").child("-KtBH9gnTszNxcXjNu9A").child("user").getValue()
Or more simply:
dataSnapshot.child("First Group"/-KtBH9gnTszNxcXjNu9A/user").getValue()
You can't skip the middle paths in the snapshot. Alternatively, you may want to listen to a location closer to the value you want:
referenceMainUrl.child("group_list/First Group/-KtBH9gnTszNxcXjNu9A");
This code runs in a loop and gives you values for all the 'user's
DatabaseReference dRef = FirebaseDatabase.getInstance().getReference().child("group_list").child("First_Group");
dRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String userName = snapshot.child("user").getValue(String.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
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) {
} };);