How to retrieve the child data from Firebase? - java

My database looks as follows, in here I want to retrieve the data inside the mylocation child (see the attached image here). But it is not working.
How to solve that?
My current code looks as this,
private void loadAddress() {
DatabaseReference ref= FirebaseDatabase.getInstance().getReference("Users");
ref.orderByChild("uid").equalTo(firebaseAuth.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
String name=""+ds.child("name").getValue();
String lat=""+ds.child("name2").getValue();
addresstv.setText(name);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

To get the data under mylocation, you use an explicit call to that child, like in the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("mylocation").child("name2").getValue(String.class);
double latitude = dataSnapshot.child("mylocation").child("latitude").getValue(Double.class);
double longitude = dataSnapshot.child("mylocation").child("longitude").getValue(Double.class);
Log.d("TAG", name + "/" + latitude + "/" + longitude);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
5555/79.8571577/6.9448882

Related

It does not fetch the required value Firebase Android

It does not fetch the required value and writes null What is wrong with the code please help
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("analysis_Client").child(searchUserId);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
userTotal = ds.child("Total").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
//Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
A picture of the firebase of the way to list the data I want to call both(Total - Rest - ProductNum)

Firebase Realtime Database not displayed when retriving to textviews in Android

onCreate() method is never executed. I just want to take the below data to 4 TextViews. "Detail" is the model class.
No errors are shown when running the app.
view_temp is an activity.
this is firebase realtime db
this is the java class
`public class view_temp extends AppCompatActivity {
private view_temp viewTemp;
public Detail detail;
private TextView roomtemp, roomhuminity, bodypulse, bodytemp;
private DatabaseReference mDatabase;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_temp);
mDatabase = FirebaseDatabase.getInstance().getReference("heat-stroke-device");
roomtemp = (TextView) findViewById(R.id.txt_room_temp);
roomhuminity = (TextView) findViewById(R.id.txt_huminity_temp);
bodypulse = (TextView) findViewById(R.id.txt_body_pulse);
bodytemp = (TextView) findViewById(R.id.txt_body_temp);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
detail = postSnapshot.getValue(Detail.class);
String rtemp = detail.getRoomtemp();
String rhumidity = detail.getRoomhumidity();
String bpulse = detail.getBodypulse();
String btemp = detail.getBodytemp();
roomtemp.setText(rtemp);
roomhuminity.setText(rhumidity);
bodypulse.setText(bpulse);
bodytemp.setText(btemp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
}
}`
There is no need to add the name of the project in the getReference() method. To get those names and the corresponding values correctly, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.getKey();
double value = ds.getValue(Double.class);
Log.d("TAG", name "/" + value);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
RoomHumi/86.0
RoomTemp/30.8
bodyPulse/126.0
bodyTemp/29.0
If the keys are always fixed, then simply use:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double roomHumi = dataSnapshot.child("RoomHumi").getValue(Double.class);
Log.d("TAG", "RoomHumi" "/" + valueroomHumi);
double roomTemp = dataSnapshot.child("RoomTemp").getValue(Double.class);
Log.d("TAG", "RoomTemp" "/" + roomTemp);
double bodyPulse = dataSnapshot.child("bodyPulse").getValue(Double.class);
Log.d("TAG", "bodyPulse" "/" + bodyPulse);
double bodyTemp = dataSnapshot.child("bodyTemp").getValue(Double.class);
Log.d("TAG", "bodyTemp" "/" + bodyTemp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
And you'll have the same result in the logcat.
Just change your line
mDatabase = FirebaseDatabase.getInstance().getReference("heat-stroke-device");
to
mDatabase = FirebaseDatabase.getInstance().getReference();
Note: You do not need to put your database name into reference.

how do I display all markers from the firebase database?

how do I display all markers from the firebase database?
I have come into the database the data in this form:
but only what is highlighted in the drawing is displayed! I write the code like this:
#Override
public void onMapReady(GoogleMap googleMap) {
if (!isOnline() && !isNetworkAvailable()) {
} else {
Map1 = googleMap;
Map1.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Map1.setMapStyle(mapStyleOptions);
Map1.setOnMyLocationButtonClickListener(this);
Map1.setOnMyLocationClickListener(this);
if (Map1 == null) {
Map1.setMyLocationEnabled(true);
}
startCurrentLocationUpdates();
mHandler.postDelayed(new Runnable(){
public void run(){
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Markers");
Map.clear();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()) {
String latitude = ds.child("latitude").getValue().toString();
String longitude = ds.child("longitude").getValue().toString();
String bus = ds.child("bus_station").getValue().toString();
Log.d("TAG", latitude + ", " + longitude);
LatLng location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
Map.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.img_4662878)).position(location).title(bus));
}}}}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
mHandler.postDelayed(this, delay);
}
}, delay);
}}
tell me how to display all markers from the database correctly?
error:
2020-04-22 23:10:12.031 18972-18972/by.sviter.stop E/AndroidRuntime: FATAL EXCEPTION: main
Process: by.sviter.stop, PID: 18972
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at by.sviter.stoprevizor.tabs.maps.MapsFragment$3$1.onDataChange(MapsFragment.java:337)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database##19.2.1:179)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.1:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.1:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6718)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Assuming that dn4O ... mgG2 is the uid of the authenticated user, to get the values of the latitude and longitude properties, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Markers").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String latitude = dataSnapshot.child("latitude").getValue(String.class);
String longitude = dataSnapshot.child("longitude").getValue(String.class);
Log.d("TAG", latitude + ", " + longitude);
LatLng location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
//Do what you need to do with the location
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logat will be:
53.9148950..., 27.4380507...
Edit:
According to your comment:
how to show all the tags?
Please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference markersRef = rootRef.child("Markers");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String latitude = ds.child("latitude").getValue(String.class);
String longitude = ds.child("longitude").getValue(String.class);
Log.d("TAG", latitude + ", " + longitude);
LatLng location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
//Add the location to a list of locations
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
markersRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
// ...
// ...
53.9148950..., 27.4380507...
After the scope of DataSnapshot for loop has ended you can manipulate the contents of the DataModel object using the getters and setters which you should have implemented.
If this does not work. Check if you mMarkers1 object is pointing to the correct class, or change the addListenerForSingleValueEvent to addValueEventListener.
You should you use addValueEventListner instead of addListenerForSingleValueEvent
You must run a for loop to get all data like...
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Markers").addValueEventListner(new ValueEventListner{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snap : dataSnapshot.getChildern()){
cast into your model class
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Get user list from table-1, then compare with data from table-2

I get user list from data-1 table as seen in code below.
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference reference = rootReference.child("data-1")
ValueEventListener listener= new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final ArrayList<String> userList= new ArrayList<>();
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String foundUserId= dSnapshot.getKey();
if (condition) {
userList.add(foundUserId);
//step one completed: userList is full with all necessary users
//Now how to iterate it and compare it with data from table-2?
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
reference.addListenerForSingleValueEvent(listener);
}
So far so good, userList has all the users found from data-1 table. But, I still need to filter out some users and add them to second list called filteredUserList. I need to filter them out by comparing each user to the current user that's saved on the final variable currentUserId
I get list of users from data-1, where each user has a list of users under it like so:
data-1
|_____uid1
| |_____uid3: true
| |_____uid4: true
|
|_____uid25
|_____uid34: true
|_____uid101: true
You see in data-1 each user has a list of users under it, which is how I first get to fill userList.
table-2 has timestamp node, and this is its structure:
table-2
|
|____userid1
| |
| |_____timestamp: timestamp
|
|____userid2
|
|_____timestamp: timestamp
//and so on..
What I want to do is, after I have userList filled with users, I need to check whether each user's timestamp is within a certain time delta from the current user. So I need to iterate the userList, and compare each user's timestamp with the current user's timestamp. But I can't get it to work because in order to get each user's timestamp I need a new onDataChange, and in a for loop, but it's out of scope, and it's also async so it's never working! What would be the correct way to make it work? I've been trying for over a week now. Is it even possible to do that?
The simplest solution I can think of is to get current user timestamp and then query the entire users node and compare current user timestamp with the other user timestamps.
I need to filter them out by comparing each user to the current user
So to solve this, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users")
DatabaseReference uidRef = usersRef.child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long currentUserTimestamp = dataSnapshot.child("timestamp").getValue(Long.class);
String currentUserKey = dataSnapshot.getKey();
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
long timestamp = dataSnapshot.child("timestamp").getValue(Long.class);
if(currentUserKey != ds.getKey()) {
if(currentUserTimestamp > timestamp) {
//Do something
} else {
//Do something else
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
Edit: Accoding to the comments and edited question, please see the code below:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference table2Ref = rootRef.child("table-2");
DatabaseReference uidRef = table2Ref.child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long currentUserTimestamp = dataSnapshot.child("timestamp").getValue(Long.class);
String currentUserKey = dataSnapshot.getKey();
DatabaseReference currentUserKeyRef = rootRef.child("data1").child(currentUserKey);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
DatabaseReference userKeyRef = table2Ref.child(userKey);
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot d : dataSnapshot.getChildren()) {
long timestamp = d.child("timestamp").getValue(Long.class);
if(currentUserTimestamp > timestamp) {
//Do something
} else {
//Do something else
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
userKeyRef.addListenerForSingleValueEvent(listener);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
currentUserKeyRef.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

Retrieve specific value from Firebase database into string variable

I'm trying to retrieve a specific value from a Firebase realtime Database.
The data looks like this:
I want to get the URL value from any of them and then put it into a string variable to use later. This is so that the program does not need to be changed if the download link is changed. The code I have so far is;
DatabaseReference fdb = FirebaseDatabase.getInstance().getReference();
//Query query = fdb.child("URLDOWNLOADS").child("WSSeasons")
fdb.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot url : dataSnapshot.getChildren())
{
LoginInfoFirebasedb DownURL = url.getValue(LoginInfoFirebasedb.class);
String temp = DownURL.dwldURL;
URL1 = temp;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
Some help would be seriously appreciated. I understand this may be a simple problem but I am stumped.
To get each url as a String, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("URLDOWNLOADS");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
String url = ds.child("URL").getValue(String.class);
Log.d(TAG, key + " / " + url);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
ref.addListenerForSingleValueEvent(valueEventListener);

Categories

Resources