Reading data from firebase database fails - android

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

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

2 different android apps in 1 Firebase Project

Image.png
> I have a Client app and Driver app under 1 Firebase Project.
This link is only said yes it can be done, but how can it be done?? not stated
Two different google-services.json
One Firebase Database for both
When from Customer app order is made, it is saving to Database as a child("Orders"), and as a test, I can retrieve those Orders in Customer app.
But how to retrieve those Orders in Driver app??
This is a piece of code, in Driver app which tries to retrieve data from Customer app.
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("Orders");
final ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String surname = ds.child("surname").getValue(String.class);
String beverages = ds.child("beverages").getValue(String.class);
String deserts = ds.child("deserts").getValue(String.class);
String time = ds.child("time").getValue(String.class);
edtx_name.setText(name);
edtx_surname.setText(surname);
edtx_beverages.setText(beverages);
edtx_deserts.setText(deserts);
edtx_time.setText(time);
Log.d("Test", "" + edtx_name + "/" + edtx_surname + "/" + edtx_beverages + "/" + edtx_deserts + "/" + edtx_time);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
rootRef.addListenerForSingleValueEvent(eventListener);
But this doesnt retrieve. what am i making wrong?

Query child value when you don't know parent Key

I am trying to query a child node value but I don't know parent key, I want to query for Firebase Adapter. I want to access userid node under area but I don't know the Id of parent i.e -KqPJMsjSb5CbPcq4nXv
Here is the snapshot of Record:
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userIdRef = rootRef.child("areas").child(userId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String areaId = ds.child("areaId").getValue(String.class);
Boolean booked = ds.child("booked").getValue(Boolean.class);
Integer bookingHour = ds.child("bookingHour").getValue(Integer.class);
//and so on
Log.d("TAG", areaId + " / " + booked + " / " + bookingHour);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userIdRef.addListenerForSingleValueEvent(eventListener);
In which userId is the id of the user that said that is not missing.
When you execute a query against the Firebase Database, there will potentially be multiple results.
So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

How do I retrieve data from firebase database and show in custom listview?

I have stored user posts details in Post node under USERID in firebase database accordingly in incremental order as Post1, Post2 so on. Now I want to retrieve all the data within Post node one by one in descending order as Post2, Post1 and show in custom listview. For retrieving single post node data it is working fine but not working for retrieving multiple/all post nodes.
Here is my firebase database image:
For showing all the posts i have tried this way:
dataref1.addValueEventListener(new
com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot
dataSnapshot) {
list.clear();
for(com.google.firebase.database.DataSnapshot dataSnap :
dataSnapshot.getChildren())
{
for(com.google.firebase.database.DataSnapshot datas :
dataSnap.getChildren()) {
DataModel datamodel =
dataSnap.getValue(DataModel.class);
list.add(datamodel);
}
}
CustomAdapter adapter = new CustomAdapter(Home.this,list);
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
It is just showing the user name in custom listview.
I have checked many tutorials but haven't find the solution. Kindly help me out.
Thank you :)
To display those posts you need to change a little bit your Firebase database. For the moment all your posts are nested under the uid. You need to add another node, named posts, a direct child of the uid, in which you need to add all those post separately. Your database should look like this:
Firebase-root
|
---- city: "City Name"
|
---- email: "name#email.com"
|
---- //and so on
|
---- posts
|
---- post1
|
---- post2
|
---- post3
|
//and so on
To diplsy those posts, please use this code:
//get the uid
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
String uid = firebaseUser.getUid();
}
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child(uid).child("posts");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String description = ds.child("description").getValue(String.class);
String dateTime = ds.child("dateTime").getValue(String.class);
String posturi = ds.child("posturi").getValue(String.class);
String severity = ds.child("severity").getValue(String.class);
Log.d("TAG", description + " / " + dateTime + " / " + posturi + " / " + severity);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
FirebaseUI library make it very easy. Allow you to use FirebaseRecyclerAdapter to populate a RecyclerView
Here the official guide
FirebaseUI

Reading from a simple FireBase Database

I'm having some issues reading from a Firebase Database.
I have a pretty simple layout
{
"lot" : {
"lot1" : "low",
"lot2" : "low",
"lot3" : "low"
}
}
Of course MyAppName { } is above this all.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getInstance().getReference();
// Read from the database
myRef.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.
lotMap = (HashMap) dataSnapshot.getValue();
Log.d("[Directions Activity]: ", "Lot1 value ====== " +lotMap.get("lot"));
Iterator it = lotMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
Log.d("[Directions Activity]: ", "iterator " + pair.getKey() + " = " + pair.getValue());
System.out.println();
it.remove(); // avoids a ConcurrentModificationException
}
}
Here's what returns from log
D/[Directions Activity]:: Lot1 value ====== null //null obviously
//because key lot1 doesn't exist
D/[Directions Activity]:: lot = {lot3=low, lot2=low, lot1=low}
So to me, it looks like it's returning the string {lot3=low, lot2=low, lot1=low}, but I'd like to be able to get an array, with each value if possible.
Is this achievable??
I had the same question and this is what i used. Modifying to fit the question here
private List<String> lotList;
lotList = new ArrayList<>();
DatabaseReference reference= database.getInstance().getReference().child("lot");
Now adding value event listener
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> mData = dataSnapshot.getChildren();
for(DataSnapshot d : mData){
String lot_string = d.getValue(String.class);
lotList.add(lot_string);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
There's some tweak in your code. Your
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getInstance().getReference();
should be write like this,
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference database = myRef.child("anyValueNameYouSpecifyInConsole");
Those 2 lines should be declare outside onCreate method. The one that you need to specify with addValueEventListener is the 2nd DatabaseReference, not the first one. So, it should looks like this from my example,
database.addValueEventListener (new ValueEventListener)
and it will import method.
If you wish the data to be displayed in a particular TextView, then just findViewById the TextView you wanna use and include it in onDataChange method like so,
String x = dataSnapshot.getValue(String.class);
textViewNameDeclared.setText(x);
And don't forget to change the security rule for reading.
you can use typecast to JSONObject and parse the JSONObject
JSONObject jsonObject= new JSONObject((Map)dataSnapshot.getValue());
JSONObject jsonObj= (JSONObject) jsonObject.get("lot");
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
}
if you using java 8 than you use lamada expression.

Categories

Resources