In the picture is my database, so I want to retrieve the value of latitude and longitude from my databasem but the child name is named from random time based on the time when the data uploaded.
How can I get the value of latitude and longitude when I don't know what time that the child used because it's random time?
You want to fetch all data or any specific data?
EDIT:
FirebaseDatabase.getInstance().getReference().child("History").child("Saturday").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String lat = snapshot.child("Latitude").getValue().toString();
String longi = snapshot.child("Longitude").getValue().toString();
//OR you can typecast the entire snapshot object into your model class
ModelClass model = new ModelClass();
model = snapshot.getValue(ModelClass.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Related
I have a String stationName and I want to fetch distance from FireBase according to the stationName I provided.
Here is my Firebase Database:
I am using orderByChild query to filter result and I need fetch only the distance value. Here is my code:
Query query = FirebaseDatabase.getInstance().getReference("Stations").orderByChild("Name").limitToFirst(1).equalTo(sourceName);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String distance;
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
distance = dataSnapshot.child("Distance").getValue(String.class);
tt.setText(distance); //to check if it is working or not
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I need to know what is wrong with code. It's not returning any value.
Thanks in advance
Replace this
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
distance = dataSnapshot.child("Distance").getValue(String.class);
tt.setText(distance); //to check if it is working or not
}
With this
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
distance = snapshot.child("Distance").getValue().toString(); // you
//cannot pass the String.class as in the getValue() parameters becasue a long value
//can not be cast to class object so you need to call toString() method to convert long value
//into the string value.
tt.setText(distance); //to check if it is working or not
}
Hope it helps
I have a list of objects on my Firebase database, and the key for each object is a timestamp. I can get the last one using limitToLast(1), and the data snapshot I get is:
{ key = time_stamps, value = {1510768441759={id=f454445c6e880df31e, coordinates={latitude=-4.1461734, longitude=20.5992437}}} }
Where 1510768441759 is the timestamp.
How do I read the coordinates? I've tried to convert the value to a POJO, but I cannot, because the timestamp is unknown to me, and in a POJO it would be the name of a property…
Thanks.
If you do it without a parent POJO but only with coordinates pojo you can just do the following by the datasnapshot:
Query query = ref.child("time_stamps").orderByKey();
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot item: dataSnapshot.getChildren()){
if (!dataSnapshot.hasChildren()) {
return;
}
for(DataSnapshot childSnapShot :item.getChildren()){
final String timestamp = childSnapShot.getKey();
final DataSnapshot parentSnapShot = childSnapShot.child(timestamp);
if (!parentSnapShot.hasChildren()) {
continue;
}
Double latitude = parentSnapShot.child("latitude").getValue(Double.class);
Double longitude = parentSnapShot.child("longitude").getValue(Double.class);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
etc.
You have:
time_stamp
1510768441759
id: f454445c6e880df31e
coordinates
latitude=-4.1461734
longitude=20.5992437
try this, assuming you do not have this 1510768441759 :
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("time_stamp");
Query query = reference.orderByChild("id").equalTo(f454445c6e880df31e );
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
for(DataSnaphot ds :datas.getChildren()){
String latitudes=ds.child("latitude").getValue().toString();
String longitudes=ds.child("longitudes").getValue().toString();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The above is done assuming you are on this datasnasphot time_stamp. First you do a query to be able to get the coordinates of this id: f454445c6e880df31e. Then since you are on this datasnasphot time_stamp, you have to loop once to be able to retrieve this 1510768441759, then loop again to be able to get the latitude and the longitude.
I 'm trying to retrive all Posts(Root child) data..using datasnapshot along with Map.....
but only Problem is- a single entry data is repeated
others entries are not shown..i don't know why?
i think some mistakes occuring here..
pleae help me out, thanks!
My code looks like-
mPostDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot!=null) {
Map<String,Object> all_users_IDs=(HashMap<String,Object>) dataSnapshot.getValue();
//iterate through each user, ignoring their UID
for(Map.Entry<String, Object> entry : all_users_IDs.entrySet()){
//Get single user map
Map singleUser = (Map) entry.getValue();
String date= (String) singleUser.get("Date");
String posted_img= (String) singleUser.get("PostedImage");
String desc= (String) singleUser.get("Description");
holder.setPostedImg(posted_img, getContext());
holder.setDate(date);
holder.setDescription(desc);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
try this..
for (DataSnapshot data : dataSnapshot.getChildren()) {
// code here
}
Here member’s key in Group is User’s key.
Task: Want to fetch comida_id froenter code herem User based on Group’s member key.
Here we are trying to first fetch member keys from Group. While fetching member key we also want to fetch User and User’s comida_id while that member’s loop is going. So the scenario will be First we are going to fetch all keys from Group based on Group’s key ( for example createTime, groupName, members ). Now from that we will execute loop on members so will get member’s key. Now while fetching this member’s key in that loop, we want to fetch comida_id from User’s, which will be fetch in that loop only.
GroupKey -> get Data(createTime, groupName, members, restaurants) -> fetch members key and comida_id ( in Loop (get member key then fetch comida_id ))
*My Code
FirebaseDatabase mDatabase_gp = FirebaseDatabase.getInstance();
mDatabase_gp.getReference("Group/"+group_key).addValueEventListener(
new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Map<String, Object> valuesMap = (HashMap<String, Object>) dataSnapshot.getValue();
Map userkey = (Map) valuesMap.get("members");
Log.d("Members", String.valueOf(userkey));
for (Object ke: userkey.keySet())
{
Log.d("runfirst","First Run");
String key = String.valueOf(ke.toString());
Log.d("Member key",key);
// HERE WHAT CORRESPONDS TO JOIN
FirebaseDatabase User = FirebaseDatabase.getInstance();
User.getReference("User/"+key).addValueEventListener(
new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Map<String, Object> valuesMap = (HashMap<String, Object>) dataSnapshot.getValue();
String userid = String.valueOf(valuesMap.get("comida_id"));
Log.d("comida_id",userid);
Toast.makeText(ChatSectionActivity.this,userid,Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
}
);
}
Log.d("runlast","Last Run");
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
}
);
*
In Above code we tried to achieve same thing but here this code will fetch all member keys from group first. After fetching all members it will fetch comida_ids in another loop.. So there will be like two different loops working to fetch comida_id from members. It’s not working like join query.
GroupKey -> get Data(createTime, groupName, members, restaurants) -> fetch members key (in Loop (get member key) after then fetch comida_id .
*1) I was try this solution - How to perform join query in Firebase?
**But get this error –
Incompatible types.
Required: com.google.firebase.database.DatabaseReference
Found: com.google.firebase.database.ValueEventListener
https://i.stack.imgur.com/ljlWo.png
Firebase doesn't have join queries. And what you are doing wrong is your are referencing your data base on Fireabaseuser, which is wrong.
mdatabaseReference.child("Answer").child("Answer"+QID).orderByChild("questionId").equalTo(QID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (muftiAnswer_List.size() > 0)
muftiAnswer_List.clear();
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
final AnswerClass muftiAnswer = postsnapshot.getValue(AnswerClass.class);
String ide=muftiAnswer.getMuftiId(); //getting AlimId From Class object
Log.e(TAG, "Alim:"+ muftiAnswer.getMuftiId());
//Using Query to get Alim Name From Data Table.!
mdatabaseReference.child("users").child("Alim").child(ide).addListenerForSingleValueEvent(new ValueEventListener() {
#Override //.orderByChild("alimId").equalTo(user_Id)
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "AlimNode:");
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
Log.e(TAG, "EqualNode:");
if(postSnapshot.getKey().equals("alimName"))
{
Log.e(TAG, "AlimNameNodeSnapShot:");
//Setting Alim Name in Current Object replcing id for name
muftiAnswer.setMuftiId(postSnapshot.getValue().toString());
}
// resultMuftiAnswer_List.add(muftiAnswer);
}//End of snapshot
}//ondata Change
#Override
public void onCancelled(DatabaseError databaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});//End OF Alim Query
}//end of comments
circular_progress2.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Details_Activity.this, "LOLOLOL", Toast.LENGTH_SHORT).show();
}
});
You have to use nested loops for doing joins like MYSQL
Query query = reference.child("issue").orderByChild("id").equalTo(0);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Visit link for better understanding
https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html
So I have a list of objects stored in firebase and want to query for just one object using child equal to method but I am getting a map with single key value instead.
Code below showing what I want to achieve instead of dealing with hashmaps.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference coutryRef = database.getReference(FireContract.PATH_COUNTRY);
Query countryQuery = coutryRef.orderByChild(FireContract.CHILD_NAME)
.equalTo(TestUtilities.TEST_COUNTRY_ALGERIA).limitToFirst(1);
countryQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Country country = dataSnapshot.getValue(Country.class);
assertEquals(TestUtilities.TEST_COUNTRY_ALGERIA, country.getName());
//get country key
String coutryKey = dataSnapshot.getKey();
}
#Override
public void onCancelled(DatabaseError databaseError) {
fail("Failed to get country: " + databaseError.getMessage());
}
});
When you fire a query, you will always get a list of results. Even when there is only a single item matching the query, the result will be a list of one item.
To handle the list, you can either use a ChildEvenListener or you can loop over the children in your ValueEventListener:
countryQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot countrySnapshot: dataSnapshot.getChildren()) {
Country country = countrySnapshot.getValue(Country.class);
assertEquals(TestUtilities.TEST_COUNTRY_ALGERIA, country.getName());
//get country key
String countryKey = countrySnapshot.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
fail("Failed to get country: " + databaseError.getMessage());
}
});