This is my firebase-database.
Query lastQuery = databaseReference.child("rawlocations").child("12345678").limitToLast(1);
lastQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Double latt= (Double) dataSnapshot.child("lat").getValue();
Double lngg= (Double) dataSnapshot.child("lng").getValue();
LatLng location=new LatLng(latt,lngg);
});
In this database locations are updating for every 10 meters.Now i want to refer the very recently updated location?How can i refer this in my code?Anyone can help?
If you want to get the latitude and longiture of a single id, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference idRef = rootRef.child("raw-locations").child("12345678");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
double lat = ds.child("lat").getValue(Double.class);
double lng = ds.child("lng").getValue(Double.class);
Log.d("TAG", lat + " / " + lng);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
idRef.addListenerForSingleValueEvent(eventListener);
If you want all ids, you need to loop twice.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference rawRef = rootRef.child("raw-locations");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
for(DataSnapshot dSnapshot : ds.getChildren()) {
double lat = dSnapshot.child("lat").getValue(Double.class);
double lng = dSnapshot.child("lng").getValue(Double.class);
Log.d("TAG", lat + " / " + lng);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
rawRef.addListenerForSingleValueEvent(eventListener);
Try this, it works in my code and feth every value from my childs
mDatabase.child("raw-locations").child("12345678").addValueEventListener(new ValueEventListener() {
final List<String> lstItems= new ArrayList<String>();
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = (String) ds.getKey();
String values = (String) ds.getValue();
Log.e("Values",""+values );
lstItems.add(values );
}
also you can change this line
String values = (String) ds.getValue();
with this
String Latvalue = (String) ds.child("lat").getValue();
Related
I have save data of users to firebase database with hashmap.
Users's data is ordered by their ID's.
Saving code is:
emailauth = FirebaseAuth.getInstance();
donorid= emailauth.getCurrentUser().getUid();
mrefrnce= FirebaseDatabase.getInstance().getReference().child("Users").child("Donor").child(donorid);
HashMap hmap= new HashMap();
hmap.put("user_name",usern);
hmap.put("bloodgroup",bld);
hmap.put("user_address",address);
hmap.put("user_type","Blood Donor");
mrefrnce.updateChildren(hmap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Toast.makeText(MakeDonorProfile.this,"Data has been Saved",Toast.LENGTH_SHORT).show();
progress.dismiss();
Intent intent= new Intent(MakeDonorProfile.this, PlacePick.class);
startActivity(intent);
}
}
});
In the above code i have saved data by donor id
This is retrieving code
DatabaseReference donordRef = FirebaseDatabase.getInstance().getReference().child("Users").child("Donor");
donordRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long size = dataSnapshot.getChildrenCount();
for (DataSnapshot child : dataSnapshot.getChildren()) {
getDonorData donordata = dataSnapshot.getValue(getDonorData.class);
String latitude = child.child("latitude").getValue().toString();
String longitude = child.child("longitude").getValue().toString();
String bloodgroup = child.child("bloodgroup").getValue().toString();
String do_address = child.child("user_address").getValue().toString();
String donarname = child.child("user_name").getValue().toString();
double loclatitude = Double.parseDouble(latitude);
double loclongitude = Double.parseDouble(longitude);
LatLng cod = new LatLng(loclatitude, loclongitude);
mMap.addMarker(new MarkerOptions().position(cod).title( donarname).snippet("Blood Group: "+bloodgroup+"\n"+"Address: "+do_address));
mMap.setInfoWindowAdapter(new InfoWindowAdapter(SearchActivity.this));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now in retrieving code i want to get donor id with other data.
How I can get this id for all donors in DataSnapshot for loop?
Database picture is click database picture
Thanks in Advance
Regards
Ahsan Sherazi
I think this might help.
DatabaseReference databaseRef = databaseReference.child("Donor");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren())
Log.d("GetDonorId","DataSnapshot :"+dataSnapshot1.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have this data structure:
The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.
I have tried different methods for showing only the animals that have id that is stored in the current user node.
Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".
Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.
myAnimalRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG1, "failed to read value: " + databaseError.toException());
}
});
How can get my code to filter out every animal that does not have their ID in the user node?
The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.
To achieve this, you need to query your database twice. Please use the following code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = usersRef.child("users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String aid = ds.getKey();
DatabaseReference animalRef = rootRef.child("animals").child(aid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dSnapshot) {
int age = dSnapshot.child("age").getValue(Integer.class);
String name = dSnapshot.child("name").getValue(String.class);
String url = dSnapshot.child("url").getValue(String.class);
Log.d("TAG", age + " / " + name + " / " + url);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
animalRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
In which uid is the id of the logged-in user and aid is the id of the animal. Your output will be:
11 / dog1 / http...
12 / dog2 / http...
Hope you find this helpfull.!
Get Object in Your Model Class and Store that Object in List for Further user.!
You can get specific object as well simple using
mdatabaseRef.child("animals").orderByChild().equalTo("value")
and also you can add check on key by orderByKey()
private FirebaseAuth mAuth;
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseRef;
mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();
ArrayList<User> allUserList = new ArrayList<>();
Array<Animal> allAnimalList=new ArrayList<>();
mdatabaseRef.child("animals").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
Animal animal = childSnapshot.getValue(Animal.class);
allAnimalList.add(animal );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mdatabaseRef.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
User user = childSnapshot.getValue(User .class);
allUserList.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I ended up taking Alex Mamo's answer and tweak with a litte bit.
This is the code i'am using:
uid = currentUser.getUid();
mRootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference myUserRef = mRootRef.child("users").child(uid);
Log.d(TAG1, uid);
myUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
String aid = ds.getKey();
DatabaseReference myAnimalRef = mRootRef.child("animals");
Query query = myAnimalRef.orderByKey().equalTo(aid);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds2 : dataSnapshot.getChildren()){
AnimalCard value = ds2.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The main difference is that i'am using a query to filter out every Animal that does not have the aID that the currentUser have.
This is my data structure:
Here I want to retrieve the Latitude and Longitude of the last item of Location child based on the id = "sd".
Here's the code:
Query query = mDatabase.child("Users").orderByChild("Id").equalTo(busId);
// busId = "sd"
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot user : dataSnapshot.getChildren()) {
Query lastItem = user.getRef().child("Location").orderByKey().limitToLast(1);
lastItem.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lat = dataSnapshot.child("Latitude").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
break;
}
}
How can I do that? Thanks
Please use this code for Android:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String Id = ds.child("Id").getValue(String.class);
if(Id.equals("sd")) {
Query q = ds.child("Location").getRef().orderByKey().limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child : dataSnapshot.getChildren()) {
Double latitude = child.child("Latitude").getValue(Double.class);
Double longitude = child.child("Longitude").getValue(Double.class);
Log.d("TAG", latitude + " / " + longitude);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
q.addListenerForSingleValueEvent(valueEventListener);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
How do I find user data from Firebase database?
This is how my database looks like:
I'm saving my data under tokens:
String token = FirebaseInstanceId.getInstance().getToken();
if (token == null) return;
databaseReference = FirebaseDatabase.getInstance().getReference(token);
I need to find all location coordinates from all users and set up marker, but everything that I made, it's accessing to current user:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(FirebaseInstanceId.getInstance().getToken());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()){
double allLat = (double) dataSnapshot.child("lat").getValue();
double allLng = (double) dataSnapshot.child("lng").getValue();
mMap.addMarker(new MarkerOptions().position(new LatLng(allLat, allLng)).title("Пользователь"));}
}
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference();
userRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
HashMap<String,Object> hm = (HashMap<String, Object>) dataSnapshot.getValue();
String allLat = String.valueOf(hm.get("lat"));
String allLng = String.valueOf(hm.get("lng"));
Log.e("!_#_#------> ", allLat + " " + allLng);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get Latitude and longitude and data of all devices like 6430046874, 6430046875, 6430046876.
new GetDataFromFirebase().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference("GPSLocationHistory/DevicesLatest/6430046874");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> objectHashMap = dataSnapshot.getValue(objectsGTypeInd);
ArrayList<Object> objectArrayList = new ArrayList<Object>(objectHashMap.values());
System.out.println("value 0= " + objectArrayList.get(0) + " value 1= " + objectArrayList.get(1) + "value 2= " + objectArrayList.get(2) + " value 3= " + objectArrayList.get(3) + "value 4= " + objectArrayList.get(4) + " value 5= " + objectArrayList.get(5) + " value 6= " + objectArrayList.get(6));
// LatLng location = new LatLng(latitude, longitude);
String latLng = objectArrayList.get(2).toString() + "," + objectArrayList.get(3).toString();
System.out.print("oyy " + latLng);
Toast.makeText(MapsActivity.this,""+latLng.toString(),Toast.LENGTH_SHORT).show();
latlongFcm = new LatLng(Double.parseDouble(objectArrayList.get(2).toString()), Double.parseDouble(objectArrayList.get(3).toString()));
mMap.clear();
Marker marker;
marker = mMap.addMarker(new MarkerOptions()
.position(latlongFcm)
.title("San Francisco")
.snippet("Population: 776733"));
for (DataSnapshot alert : dataSnapshot.getChildren()) {
System.out.println(alert.getValue());
}
}
This code will show only data of one User like 6430046874
i want to make Model class and get data from here of all the user and plot the markers.
Step 1) Make a PoJo.class which contains all the keys that are in DeviceLatest child node with similar datatype
Step 2) Go to desired child node here in your scenario it is GpsLocationHistory-DeviceLatest. so here we have to take two time child ..Please correct the spelling of child node
Step 3) Write down below method and call.
public void getAllUsersFromFirebase() {
DatabaseReference UserRef = FirebaseDatabase.getInstance().getReference().child("GpsLocationHistory").child("DeviceLatest");
UserRef.keepSynced(true);
UserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
List<PoJo> fcmUsers = new ArrayList<>();
while (dataSnapshots.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshots.next();
PoJo fcmUser = dataSnapshotChild.getValue(PoJo.class);
fcmUsers.add(fcmUser);
}
// Check your arraylist size and pass to list view like
if(fcmUsers.size()>0)
{
fcmUsers arraylist pass to list view
}else
{
// Display dialog for there is no user available.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// for handling database error
}
});
}
You get only one because you did not iterate over the entire object. So in order to solve this, please use this code:
FirebaseDatabase database = FirebaseDatabase.getInstance().getReference();
DatabaseReference myRef = database.child("GPSLocationHistory").child("DevicesLatest");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String deviceId = (String) ds.getKey();
DatabaseReference deviceIdRef = database.child("GPSLocationHistory").child("DevicesLatest").child(deviceId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Double lati = (Double) dataSnapshot.child(lati).getValue();
Double longi = (Double) dataSnapshot.child(longi).getValue();
//and so on for the other values
//and do what you want with this values
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
};
deviceIdRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
};
myRef.addListenerForSingleValueEvent(eventListener);