Retrieve all Users id from Firebase Database - android

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

Related

How to limit retrieve data on firebase realtime Android Studio

I want to ask about how to limit retrieve data in Android Firebase. Here is my code:
private void lookingforHelp(){
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Locations");
dbref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
int limitUser = 0;
ModelUsersLocation mUserLoct = ds.getValue(ModelUsersLocation.class);
LatLng yourLatLng = new LatLng(latitude_user, longitude_user);
LatLng polisiLatLng = new LatLng(mUserLoct.getLatitude(), mUserLoct.getLongitude());
if (mUserLoct.getPengguna().equals("polisi")){
if (SphericalUtil.computeDistanceBetween(yourLatLng, polisiLatLng) < 700) {
if (limitUser <= 5){
if (mUserLoct.getJangkauan().isEmpty()) {
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Locations").child(mUserLoct.getUser().getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("jangkauan", fuser.getUid());
dbref.updateChildren(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
writeNewOrder();
}
});
}
}
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I tried to retrieve data that i want is only less than 5 users, using int limitUser = 0; and it's still not working to retrieve data only less than 5 users.
PROBLEM SOLVED, I try to create markeroptions and make it into invisible, and then add it into arraylist, if (markers.size() <= 5) {do something}
thank u guys for your help btw i really apreciate it :))
public MutableLiveData<ArrayList<Vendor>> getVendorsByLimit(int limit) {
ArrayList<Vendor> arrayList = new ArrayList<>();
Query query = FirebaseDatabase.getInstance().getReference().child("VENDOR_NODE").limitToLast(limit);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() > 0) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.getChildrenCount() > 0) {
//String value = (String) snapshot.getValue(); //Get all child data
//OR
//String singleValue = (String) snapshot.child("fullName").getValue(); //Get single child data
Vendor model = snapshot.getValue(Vendor.class);
String key = snapshot.getKey();
arrayList.add(model);
}
}
data.setValue(arrayList);
} else {
data.setValue(null);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e(TAG, "" + databaseError.getMessage());
data.setValue(null);
}
});
}
Query query = FirebaseDatabase.getInstance().getReference().child("VENDOR_NODE").limitToLast(limit);
You can sort them by using timeStamp like
-----------------------------------------
FirebaseDatabase.getInstance().getReference()
.child("Conversation").child(conversationID)
.limitToLast(100)
.orderByChild("timestamp")
.startAt(dateToStart) // pass timestamp from when you want to start filtering
.endAt(dateToEnd); // pass timestamp till when you want to apply filtering

how to retrieve data from fire base and assign to a string

I have a database in fire-base. In that I have a child node named "item1", under item1 i have two values
name
prize
I want to retrieve the name of item1 and I want to put it in a string called "foodname". How can I do that?
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
Here I tried but did not find solution
String foodname; //this string should get the value as "diary milk"
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("menu").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//This will loop through all items. Add variables to arrays or lists as required
for (DatasnapShot snap : dataSnapshot.getChildren())
{
foodname = dataSnapshot.child("name").getValue().toString();
String prize = dataSnapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You can fetch each child individually like such. Or you can make use of a Model or a Hashmap to fetch all of the data and then fetch the data you would like based on the Key
Using below code you can get food name
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String foodName = snapshot.child("name").getValue().toString();
String foodPrice = snapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Retrieving any data from Firebase requires a correct database reference and eventListeners that can work for what you want.
To know more about eventListeners visit this link.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("menu").child("item1");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// this code will get only details from item1
foodname = dataSnapshot.child("name").getValue(String.class);
String price = dataSnapshot.child("prize").getValue(Integer.class);
//if you want details from multiple items, you have to loop over the child nodes like this
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
foodname = snapshot.child("name").getValue().toString();
String price = snapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

How can I give access to certain objects in Firebase database based on id

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.

Get Last Item in nested database firebase android

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

Retrieve user data from Firebase database

I have created an Android App By which user can register and login.When a user registration is successful a Name and value will created in my database for that User. Now I want to retrieve The Data For every User separately.
To retrieve the current user's data from this structure, you need two things:
to know the uid of the current user
to then read the data from the database
In code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance.getReference(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long points = dataSnapshot.child("Points").getValue(Long.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Try this:
mDatabase.child("ezzeearn").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, String> map = (Map<String, String>) dataSnapshot.getValue();
String point = map.get("Points");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
for using iterator you can get the data for specific user
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
Try to use below method :
public void getAllUsersFromFirebase() {
DatabaseReference UserRef = FirebaseDatabase.getInstance().getReference().child("ezzeearn");
UserRef.keepSynced(true);
UserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
while (dataSnapshots.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshots.next();
String resultString = (String)dataSnapshotChild.getValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// for handling database error
}
});
}

Categories

Resources