Retrieve the 3rd node in a 5 node deep system - android

I'm trying to get the names of the sections in my Firebase database and add it to a arraylist, but it only returns null.
This is my code:
mSectionReference = database.getReference().child("/apartments/").child("/B3/").child("/sections/");
ValueEventListener sectionListner = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("sections", "onDataChange");
if (dataSnapshot.exists()) {
Log.d("sections", "snapshot exists" );
for (DataSnapshot sectionSnapshot : dataSnapshot.getChildren()) {
if (sectionSnapshot != null) {
Section section = sectionSnapshot.getValue(Section.class);
Log.d("sections", "Section created: " + section.getName());
} else
Log.d("sections", "sections null");
}
}
}
#Override
public void onCancelled(DatabaseError error) {
Log.w("failedSnap", "Failed to read value.", error.toException());
}
};
mSectionReference.addValueEventListener(sectionListner);
And this is the result of the logcat:
onDataChange
snapshot exists
Section created: null
Section created: null

To solve this, please change this line of code:
mSectionReference = database.getReference().child("/apartments/").child("/B3/").child("/sections/");
with
mSectionReference = database.getReference().child("apartments").child("B3").child("sections");
The slashes are not needed when you pass the child name as an argument.

SOLUTION:
I found that even though that there is a element in the path, it doesn't mean that there is a "object" there.
I implemented a new hashmap that saves the name of the section as a key and value, making the structure look like this:

Related

Firebase realtime database list of values retrieved

Dear Friends,
I am accessing data from a Firebase database, however I am unable to get a list of my data.
I am getting the following exception:
E/UncaughtException: com.google.firebase.database.DatabaseException: Can't convert object of type java.util.ArrayList to type com.sg.rapid.Models.AlaramData`
here is my code:
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
AlaramData usersList = dataSnapshot.getValue(AlaramData.class);
String name = usersList.getStatus();
childList.add(usersList);
// here you can access to name property like university.name
}
Log.d("", "Value is: " + childList);
//Create a List of Section DataModel implements Section
sections.add(new SectionHeader(childList, "2018", 1));
adapterRecycler.notifyDataSetChanged();
}
Thanks in advance.
Reading the error message, we can understand that the method is returning an ArrayList of your elements, then I noticed you used the wrong variable there.
It should be using postSnapshot instead of dataSnapshot. Try this:
AlaramData usersList = postSnapshot.getValue(AlaramData.class);
I have solved the issue by changing the json structure in firebase database.
the code as follows:
// Read from the database
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Log.d("", "onChildChanged:" + dataSnapshot.getKey());
sections.clear();
childList.clear();
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
AlaramData alaramData = postSnapshot.getValue(AlaramData.class);
int x = 0;
// here you can access to name property like university.name
childList.add(alaramData);
}
Log.d("", "Value is: " + childList);
//Create a List of Section DataModel implements Section
sections.add(new SectionHeader(childList, "2018", 1));
adapterRecycler.notifyDataChanged(sections);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("", "Failed to read value.", error.toException());
}
});

Firebase sorting data based on child not working

I'm trying to develop a simple application to learn firebase database.
Here is my realtime database schema
mydirectory
-contact_list
-LOyDhepB_IZlM6lZtko
mobileNumber: "9385746982"
name: "Jay"
-LOyDhetiPHalLhXrOaU
mobileNumber: "8000478912"
name: "Ravi"
-LOyDhetiPHalLhXrOaV
mobileNumber: "123456789"
name: "ABC"
-LOyDheubruATyyBp8dG
mobileNumber: "023456879"
name: "XYZ"
I want to get the list of data ordered by name
So I'm using this snippet to load the data in my android application
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("contact_list").orderByChild("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> objectMap = (HashMap<String, Object>) dataSnapshot.getValue();
Master.personList.clear();
for (Object obj : objectMap.values()) {
if (obj instanceof Map) {
Map<String, Object> mapObj = (Map<String, Object>) obj;
String name = (String) mapObj.get("name");
String mobileNumber = (String) mapObj.get("mobileNumber");
Person person = new Person(name, mobileNumber);
Master.personList.add(person);
populateListView();
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("ANDs", "Failed to read value.", error.toException());
}
});
But it does not sort data based on the alphabetical order of name
key. Am I doing anything wrong or missing something?
P.S.
I've also indexing rules (ref), but still result is same! It doesn't sort data alphabetical wise.
{
"rules": {
"mydirectory": {
"contact_list": {
"$user_id": {
".indexOn": ["name"]
}
}
},
".read": true,
".write": true
}
}
I've tried many things from other posts like this topic but nothing works! Please don't make it duplicate instead please help me to solve it!
A HashMap can only contain a key and a value. And the keys in a Map are by definition not ordered. So when you call dataSnapshot.getValue(), you're throwing away all ordering information.
To maintain the order, you'll need to loop over dataSnapshot.getChildren():
public void onDataChange(DataSnapshot dataSnapshot) {
Master.personList.clear();
for (DataSnapshot contactSnapshot: dataSnapshot.getChildren()) {
String name = contactSnapshot.child("name").getValue(String.class);
String mobileNumber = contactSnapshot.child("mobileNumber").getValue(String.class);
Person person = new Person(name, mobileNumber);
Master.personList.add(person);
}
populateListView();
}
You'll also notice that I use child(...) to get a child snapshot for a specific property and get the String value from it. Your approach for that would work too, but I find that I get better error messages when I stick to a snapshot longer (instead of converting to a Map).

Add Firebase List of Object from DataSnapshot to Array

I have stored my Images URLs on Firebase Database, as I have been reading here it was the way to go.
Now I need to retrieve the 5 Picture Objects form the List and put them into an array for later use.
So I add a SingleValueEvent to my Reference which is on UserId Node and get a DataSnapshot Object, which I check for null.
The problem is that even if I only have a list of 5 Pictures in my Database, when iterating on the DataSnapshot Object it adds 19 Picture Objects into the Array...
02-14 15:13:45.375 21952-21952/com.example I/EditProfileFragment:Picture Array : 19
What am I missing here?
The Json looks like this:
PicturesUrls {
UserID {
randomID{
pictureName : "Main Picture"
pictureUrl : "URL"
}
randomId
pictureName : "Second Picture"
pictureUrl : "URL"
randomId {
pictureName : "Third Picture"
pictureUrl : "URL"
}
}
}
Here is my Code:
ArrayList<Object> mPicturesArray = new ArrayList<>();
....
....
mPicturesUrlRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
addPicturesToArray(dataSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
private void addPicturesToArray(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
Picture picture = child.getValue(Picture.class);
mPicturesArray.add(picture);
Log.i(LOG_TAG, "One Picture added : " + picture.getPictureName());
}
Log.i(LOG_TAG, "Picture Array : " + mPicturesArray.size());
}
Hummm....
Ok so I have changed the ArrayList to a HashMap and things are working as expected now.
No idea why but...

Firebase query to find a subscriber is not working

This is how my Firebase db looks like.
subscriber
u36eD7PsOaf6uo0CGuGPBjC3Y223
children: false
empty: false
id:"u36eD7PsOaf6uo0CGuGPBjC3Y223"
name: "JACKSON"
smoker:false
I want to find the record which matches id = u36eD7PsOaf6uo0CGuGPBjC3Y223.
Below is my code and its not able to retrieve the record
Query recentPostsQuery = mRef.orderByChild("id").equalTo("u36eD7PsOaf6uo0CGuGPBjC3Y223");
recentPostsQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e("Count ", "" + dataSnapshot.getChildrenCount());
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
subscriber = postSnapshot.getValue(Subscriber.class);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Log.e count statement is returning 1 record which is correct, but looks like my query is wrong, that is why I am unable to fetch record.
Your query must return String value not a object of Subscriber, Complete object of Subscriber exsist at node - u36eD7PsOaf6uo0CGuGPBjC3Y223
// With return String value which is u36eD7PsOaf6uo0CGuGPBjC3Y223
mRef.orderByChild("id").equalTo("u36eD7PsOaf6uo0CGuGPBjC3Y223");

Querying in Firebase with equalTo condition not working

I have database structure like this in Firebase
I want to search a search on this structure based on key number and get the parent key in return. Meaning if i search for 8860124421 then i should get -KTEtSR7chN8te1WaW-W in return .
I am doing it like this in android -
final String number = "8860124421";
DatabaseReference global_user_entry_ref = ApplicationContext.getGlobalDataBaseReference()
.child("User-Entry-2").getRef(); //Reference to User-Entry-2
Query query = global_user_entry_ref.orderByChild("number").equalTo(number);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null){
for(DataSnapshot friend: dataSnapshot.getChildren()){
String firebase_id = (String) friend.getKey();
Log.d("ContactSync","handle number "+firebase_id+" "+number+" "+friend);
}
Log.d("ContactSync","handle number outer "+dataSnapshot);
//user exist
}
else {
//user_does_not_exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("ContactSync","handle number oncancel "+databaseError.getMessage());
}
});
But I am not getting proper result , dataSanpshot in onDataChange looks like this -
DataSnapshot { key = User-Entry-2, value = null }
but i want to get dataSnapShot with parent of number key.
Please help , Thanks in advance
As #Frank van Puffelen stated in comments , the problem was that i was comparing a number from code with a string in the database , which does not match , Therefore the solution is to change
final String number = "8860124421";
to
final long number = 8860124421;

Categories

Resources