Get values only from second request - java

I have a problem i get value from Firebase, but the email only fills up after activity run second time.
private ArrayList<String> currentList = new ArrayList<>();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("userTable").child(user.getUid()).child("Container");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Toast.makeText(getContext(), currentList.size(),
// Toast.LENGTH_LONG).show();
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
First time size = 0;
Second time = 3(true result);

update UI after getting response.hope now it will work fine for you
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
//Toast.makeText(getContext(), currentList.size(),
// Toast.LENGTH_LONG).show();
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Firebase listener is async, which means it will run in the background and not stop the code until you recieve a response.
In your code you don't wait for the value to be returned from the server, that why size=0.
what you need to do is check the size inside the listener and after the for loop :
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
This way you will wait for the value to be returned from firebase and then get the list size.

Related

Firebase get vaule of serial number

How to get the value of this automatically without writing each one separately.
I tried this
FirebaseDatabase.getInstance().getReference().child("Orutmen").child("episodeNumber");
but it shows null value.
This one works, but I have to write for each field:
FirebaseDatabase.getInstance().getReference().child("Orutmen").child("1").child("episodeNumber");
Here is the code
m2Database = FirebaseDatabase.getInstance().getReference().child("Orutmen");
m2Database.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = snapshot.child("episodeNumber").getValue(String.class);
Toast.makeText(EpisodeListModel.this, value, Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
You can iterate throught the children of DataSnapshot:
m2Database = FirebaseDatabase.getInstance().getReference().child("Orutmen");
m2Database.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
value = snapshot.child("episodeNumber").getValue(String.class);
Toast.makeText(EpisodeListModel.this, value, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
I figured out a way
Just added a list of strings that collects the values from the snapshot
then retrieve the value by position of item clicked >>
List<String> List = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String value = snapshot.getKey();
List.add(value);
}
Toast.makeText(EpisodeListModel.this, List.get(position), Toast.LENGTH_SHORT).show();

Getting Data from Firebase realtime database, Android Studio, Java

I am looking for a way to get data from the firebase real-time database in a format like an array[] or a String.
My database looks like this:
Link to image of database
Or:
Database
|
-->Users
|
-->UID1
-->UID2
This is at the root of the database
I want to get a list of all of the UIDs in the "Users" child.
This is the code I have so far and am a bit stuck on:
DatabaseReference databaseReference = firebaseDatabase.getReference("Users");
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String UIDs = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am a bit of a rookie as it comes to java, android studio, and firebase. I am trying to get the data in a format I know how to use like a String or an Array[] of Strings. I looked around if other people had maybe asked the same question, but I could get the answers to those questions to work/didn't understand them.
Thanks in advance for your time!
To get the a list of uids, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
list.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
I recommend you to use the list only inside the callback otherwise it will be empty. If you want to use it outside the onDataChange() method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
For your above question I will give both ways: ArrayList or String with delimiters
ArrayList<String> uids = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids.add(snapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
For String
String uids = "";
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids += snapshot.getKey() + ",";
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
This gives an output such as: uid1,uid2,uid3,.....uidn,
You can try this:
DatabaseReference ref=
FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int i = 0;
for(DataSnapshot d : dataSnapshot.getChildren()) {
name[i] = d.getKey();
i++;
}
}
}//onDataChange
#Override
public void onCancelled(DatabaseError error) {
}//onCancelled
});
name[] is an array of strings!

how to get all child nodes from firebase database?

this is my structure. i am trying to code a scoreboard for my app but i cant get the username & score. i want to safe that username & score in a sorted list to get the top 10.
this is my code: i onle get the usernames.
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Userlist = new ArrayList<String>();
// Result will be holded Here
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
for (DataSnapshot as : dataSnapshot.getChildren()) {
String userkey= as.getKey();
Userlist.add(userkey); //add result into array list
}
}
un.setText(Userlist.get(2));
}
#Override
public void onCancelled(DatabaseError error) {
}
});
Try the following:
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Userlist = new ArrayList<String>();
// Result will be holded Here
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
String userkey = dsp.getKey();
String scores = dsp.child("scorehigh").getValue().toString();
Userlist.add(userkey); //add result into array list
}
}
un.setText(Userlist.get(2));
}
#Override
public void onCancelled(DatabaseError error) {
}
});
The reference is at Users then you need to loop twice to be able to access the attributes scorehigh and username

Firebase RealTime Database Delete First 20 item

DatabaseReference newReferance = database.getReference().child("Users");
Query query = newReferance.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
if (chatMessages.size() >= 10){
for (int i= 0; i < 5; i++){
//HOW ????
}
}
recyclerAdapter.notifyDataSetChanged();
}
}
Hi Dear guys. How do I select and delete the first 5 data in a real-time database? When the ArrayList reaches a certain limit, I want to delete the first 5 data from the database. I'd appreciate it if you could help with the problem.
How do I select and delete the first 5 data in a real-time database?
You can achieve this using Firebase Query's limitToFirst(int limit):
Create a query with limit and anchor it to the start of the window
And in code should look like this:
Query query = newReferance.orderByChild("timestamp").limitToFirst(5);
See I have used this limitToFirst() method that can help you find the first 5 items. To delete them, just attach a listener and inside the onDataChange() method use the following line of code:
dataSnapshot.getRef().removeValue();
final DatabaseReference newReferance = database.getReference().child("Users");
final Query query = newReferance.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
if (chatMessages.size() >= 10){
Query query1 = newReferance.limitToFirst(5);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
database.getReference().child("Users").setValue(null);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
recyclerAdapter.notifyDataSetChanged();
}
}
Although I'm set, it's all deleted. I can't erase the items I want. All cleared.
rootRef is the firebase database reference. whose instance we have to gained before trying to delete any value. you can see the code given below.
count = 0;
rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
CommonLocationClass user = postSnapshot.getValue(CommonLocationClass.class);
if (count < 5) {
rootRef.child(user.getPhNo).removeValue();
count++;
}
}
}
}
#Override
public void onCancelled (DatabaseError firebaseError){
}
});
the CommonLocationClass is a getter setter model class i have made to make the fire-base implementation easy
you can try this it works for me
public void getDataFirebase() {
/*if (chatMessages.size() == MAX_MSJ_LIMIT){
database.getReference().child("Users").removeValue();
}*/
final DatabaseReference newRefere = database.getReference().child("Users");
Query query = newRefere.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
if (chatMessages.size() >= 10) {
Query query1 = newRefere.orderByChild("timestamp").limitToFirst(5);
query1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getRef().removeValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
It didn't just erase the first 5 data.
if (chatMessages.size() >= 10) {
Query query1 = newRefere.orderByChild("timestamp").limitToFirst(5);
query1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
ds.getRef().removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I solved the problem. With this code

Retrieving all the passenger id (user id) inside the driver's passengerRequest node in Firebase and Android Studio

I'm trying to retrieve and convert it to strings the UserIDs that are being saved within the driver's passengerRequest like in this picture:
https://imgur.com/a/F6matnZ
here is my getAssignPassenger
private void getAssignedPassenger() {
String driverID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(driverID).child("passengerRequest");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
passengerID = dataSnapshot.getValue().toString();
getAssignPassengerPickUpLocation();
}else{
passengerID = "";
if(pickupMarker !=null){
pickupMarker.remove();
}
if(AssignPassengerPickupLocationListener!= null){
AssignPassengerPickupLocationref.removeEventListener(AssignPassengerPickupLocationListener);
}}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
my problem is here in this block
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(driverID).child("passengerRequest");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
passengerID = dataSnapshot.getValue().toString();
getAssignPassengerPickUpLocation();
in the passengerID it should retrieve every userIDs that are saved in there...
how do I that?
Next problem is... IF I successfully retrieved the userIDs and how do I continue it in finding their location, here is picture of the node:
https://imgur.com/1TQQ4Ih
I already started the codes for it
here is my getAssignPassengerLocation
private void getAssignPassengerPickUpLocation() {
AssignPassengerPickupLocationref = FirebaseDatabase.getInstance().getReference().child("passengerRequest").child(passengerID).child("l");
AssignPassengerPickupLocationListener = AssignPassengerPickupLocationref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()&&!passengerID.equals("")) {
List<Object> map = (List<Object>) dataSnapshot.getValue();
double locationLat = 0;
double locationLong = 0;
if (map.get(0) != null) {
locationLat = Double.parseDouble(map.get(0).toString());
}
if (map.get(1) != null) {
locationLong = Double.parseDouble(map.get(1).toString());
}
LatLng driverLatLng = new LatLng(locationLat, locationLong);
mMap.addMarker(new MarkerOptions().position(driverLatLng).title("Pickup Location").icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher_pickup_marker)));
what should I do in this block
AssignPassengerPickupLocationref = FirebaseDatabase.getInstance().getReference().child("passengerRequest").child(passengerID).child("l");
AssignPassengerPickupLocationListener = AssignPassengerPickupLocationref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()&&!passengerID.equals("")) {
List<Object> map = (List<Object>) dataSnapshot.getValue();
double locationLat = 0;
double locationLong = 0;
is it possible to store the nodes in an Array String?
For the first one
You have to get snapshot children inside snapshot
private void getAssignedPassenger() {
String driverID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(driverID).child("passengerRequest");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
List<String> passengerIdList = new ArrayList()
for (DataSnapshot passenger Snapshot: dataSnapshot.getChildren()) {
String passengerId = passenger.getKey()
passengerIdList.add(passengerId)
}
getAssignPassengerPickUpLocation();
}else{
passengerID = "";
if(pickupMarker !=null){
pickupMarker.remove();
}
if(AssignPassengerPickupLocationListener!= null){
AssignPassengerPickupLocationref.removeEventListener(AssignPassengerPickupLocationListener);
}}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
For the second one
Actually you have to keep location same position as 'destination' instead of query in another children.
But why you need to get all users request location at the same time or inside your activity contain all users request location in one activity?
For more information:
Read and write lists
https://firebase.google.com/docs/database/android/lists-of-data
and
How to structured NoSQL
https://www.youtube.com/watch?v=v_hR4K4auoQ

Categories