Add Firebase List of Object from DataSnapshot to Array - android

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...

Related

get child nodes having large data from firebase realtime database

I want to get child of node using addValueEventListener(). when books data is few, it works properly but when books count is more than 30000 it gives error as "java.lang.RuntimeException: Firebase Database encountered an OutOfMemoryError. You may need to reduce the amount of data you are syncing to the client (e.g. by using queries or syncing a deeper path)."
Firebase data structre is as
booksData
123 (book id)
bookname : ""
writer : ""
price : ""
category : ""
publicher : ""
...
456 (book id)
bookname : ""
writer : ""
price : ""
category : ""
publicher : ""
...
.... and so on. having vast data
(Data structure & name is changed just for sample)
I tried in android as
userIDRef1.child("booksData").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.e(TAG, "in get booksData");
ArrayList<BooksWrapper> booksList = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
BooksWrapper vtw = postSnapshot.getValue(BooksWrapper.class);
booksList.add(vtw);
}
userIDRef1.child("booksData").removeEventListener(this);
Log.e(TAG, "daybooks data size is : "+booksList.size());
if (booksList.size() >0){
db.addBookData(booksList);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
is there any way to get data in chunks as first 1000 books then next 1000 & so on...? Any solution please...

Get list of values of different child

I want to obtain the values ​to show them in a recyclerview, I have tried in many ways but without fortune.
This is my firebase data.
"Users" : {
"X7aVfZH5oZbIaeyLm9FAjOSr5Gd2" : {
"images" : {
"urlImages1" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg1.jpg?alt=media&token=e26fd6a2-2be7-4a01-920e-0aed1fe06436",
"urlImages2" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg2.jpg?alt=media&token=40165918-3b46-4b22-b0ef-255965b7855d",
"urlImages3" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg3.jpg?alt=media&token=cfd7d00d-9b1a-44fd-80d4-a2947f7de743",
"urlImages4" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg4.jpg?alt=media&token=995419a7-70f7-4330-b046-d06a4d54453e",
"urlImages6" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg6.jpg?alt=media&token=ee6f566a-a9e5-4e8f-9d53-64d3f3bc97a6",
"urlImages7" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg7.jpg?alt=media&token=883a3321-fbba-49bd-aae3-14b005b4cc5b"
},
"locations" : {
"locations1" : "14.2830817 -89.7263953",
"locations2" : "14.2661424 -89.7220017",
"locations3" : "14.2846352 -89.7251991",
"locations4" : "14.2684987 -89.7266704",
"locations5" : "14.2684987 -89.7266704",
"locations6" : "14.2684987 -89.7266704",
"locations7" : "14.2684987 -89.7266704"
}
I want to get the data from "images" and "locations".
imageRef = database.getInstance().getReference("Users").child(userid);
imageRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot mData : dataSnapshot.getChildren()) {
String mImages = mData.child("images").getValue(String.class);
String mLocations = mData.child("locations").getValue(String.class);
ItemData itemData = new ItemData();
itemData.setImages(mImages);
itemData.setLocations(mLocations);
data.add(itemData);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
What I try to do is show the image and the location in a recyclerview. The "images" key contains url1, url2, url3... in the same way the "locations" key and I want to show them together in the adapter.
Please look at the image of the link
You use this code to get the data from images:
String mImages = mData.child("images").getValue(String.class);
But if we look at your JSON, the images property looks like this:
"images" : {
"urlImages1" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg1.jpg?alt=media&token=e26fd6a2-2be7-4a01-920e-0aed1fe06436",
"urlImages2" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg2.jpg?alt=media&token=40165918-3b46-4b22-b0ef-255965b7855d",
"urlImages3" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg3.jpg?alt=media&token=cfd7d00d-9b1a-44fd-80d4-a2947f7de743",
"urlImages4" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg4.jpg?alt=media&token=995419a7-70f7-4330-b046-d06a4d54453e",
"urlImages6" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg6.jpg?alt=media&token=ee6f566a-a9e5-4e8f-9d53-64d3f3bc97a6",
"urlImages7" : "https://firebasestorage.googleapis.com/v0/b/anthiefy.appspot.com/o/X7aVfZH5oZbIaeyLm9FAjOSr5Gd2%2FImages%2FImg7.jpg?alt=media&token=883a3321-fbba-49bd-aae3-14b005b4cc5b"
},
That is an entire JSON object, not merely a string. So you call will return null, since the value is not a string.
To get all image URLs from this JSON, you will need to loop over its child nodes and get the individual values from there:
for (DataSnapshot imageSnapshot: mData.child("images").getChildren()) {
System.out.println(imageSnapshot.getValue(String.class));
}
Since there can be (and are) multiple images and locations, either your ItemData will need to handle those, or you will need to select a single image and location, or you will have to convert all images/locations into a single string.

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());
}
});

Retrieve the 3rd node in a 5 node deep system

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:

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");

Categories

Resources