Firebase realtime database list of values retrieved - android

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

Related

im trying to query the id created from using push() in firebase

i am trying to get the key that i used to push information to my table. Is there any other way to JUST get the key itself.
i am trying to get the red marked key
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
if(snapshot.exists()){
Toast.makeText(getActivity(), dataSnapshot.getValue().toString() , Toast.LENGTH_LONG).show();// try to get ID
}
}}
this is what i keep on getting
is there any other possible way on how i could get the red mark, directly?
DatabaseReference bdRef = FirebaseDatabase.getInstance().getReference()
.child("Lobby").orderBy("lobbyname").equalTo("admin lobby");
bdRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Toast.makeText(getActivity(), child.getKey().toString() , Toast.LENGTH_LONG).show();// try to get ID
}
}

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:

Reading data from firebase database fails

I am reading the data from the firebase database.Following is snapshot of the data stored in database.
In the snap string starting with "8SS..." is the uid of the user. Following is the code for retrieving the data from firebase database.
//To check if uid of current user and database user matches.
Query q = FirebaseDatabase.getInstance().getReference().child("Location").child(user.getUid()).equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());
q.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "Yay!!");
User us = singleSnapshot.getValue(User.class);
String string = "Name: "+ us.getName()+"\nAddress: "+ us.getlat()+ us.getlon()+ "\n\n";
n.setText(string);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// read query is cancelled.
Log.d(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
User class contains getters and setters.
The error is that only empty Text View appears concluding reading from database fails.
How to evaluate if query is true or false?
What is the error while reading from ValueEventListener()?
I tried using this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Location").child("8SS0uk4FmiPUtXP208Tx8Cqxt2z2");
And then calling on ref.addListenerForSingleValueEvent() but still nothing gets displayed.
I tried using this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Location").child(user.getUid());
This gives dataSnapShot : "DataSnapshot={key='-Kn...', value="latitude:.., longitude:..., Name:..."}. But this is not how I expected it to be.
The database structure should have been Location --> Uid --> Name : "Jane", .. .
This is my code for inserting data in the database.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser() ;
refDatabase = FirebaseDatabase.getInstance().getReference().child("Location").child(user.getUid());
DatabaseReference newPost = refDatabase.push();
//the push() command is already creating unique key
Map<String, String> mapname = new HashMap<String, String>();
mapname.put("Name", n.getText().toString());
mapname.put("latitude", Double.toString(lat));
mapname.put("longitude", Double.toString(longt));
mapname.put("user id", user.getUid());
newPost.setValue(mapname);
I solved this question by introducing multiple for loops.
So, the snapshot of my first child was dataSnapShot : "DataSnapshot={key='-Kn...', value="latitude:.., longitude:..., Name:..."}.
Below is the code to extract all the values and keys :
mRef.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "Children" + dataSnapshot.getKey());
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
String st = singleSnapshot.getKey();
Log.d(TAG, "Yay!!" + singleSnapshot.child(st));
st = "";
int count=0;
for(DataSnapshot singleSnap : singleSnapshot.getChildren()) {
Log.d(TAG, "String" + singleSnap.getValue());
//n.setText(us.getName());
if(count==0) {
st = "Name: " + singleSnap.getValue() + '\n';
}
else if(count==1) {
st = st + "Latitude: " + singleSnap.getValue() + '\n';
}
else if(count==2) {
st = st + "Longitude: " + singleSnap.getValue() + '\n';
}
count++;
}
final TextView rowTextView = new TextView(Menu5.this.getActivity());
rowTextView.setText((CharSequence) st);
ll.addView(rowTextView);
}
}
This gives single key and value pair for every unique id of created by push.So, I had to hard code the concatenation and display as the structure will remain same throughout the app.
Why are you using equal to and then getting the current user. .child(user.getUid()) should already be your current user which gives you the value of the child you are trying to listen to.
I think the uuid's are the children of "8SSOuk.......".
So it should look something like this:
FirebaseDatabase.getInstance().getReference().child("Location").child("8SSOuk.......").child(user.getUid());

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

Categories

Resources