I want to download data from firebase. and I used the method below to use it comfortably among the activities. In mDatabase I can view data being downloaded in debug mode, but I cannot transfer it to the code I want. The piece of code I gave below always looks null. I do not know how to do it...
Thank you.
Firebase Json;
"server" : {
"time" : {
"Time" : 1617695199510
}
}
This;
mDatabase.child("/server/time/Time").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
server serverTime = null;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
serverTime = snapshot.getValue(server.class);
}
MyApplication.getInstance().setmServer(serverTime); // This code always returns null.
//I'm trying to pass the firebase value here. I am trying to pass the value here to setmServer (MyApplication).
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
hideProgressDialog();
}
});
MyApplication.java:
public server mServer = null;
private static MyApplication mInstance = null;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static MyApplication getInstance() {
return mInstance;
}
public server getmServer(){
return mServer;
}
public void setmServer(server mserver){
mServer = mserver;
}
server.java:
@IgnoreExtraProperties
public class server {
public long Time;
public server(long Time) {
this.Time = Time;
}
}
There is no need for any ".getChildren()" call to loop through the "DataSnapshot" object. You can use either the "server" class for that, or a simpler way would be to get the data directly from the property using the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference timeRef = rootRef.child("server/time/Time");
timeRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
long time = task.getResult().getValue(Long.class);
Log.d(TAG, "time: " + time);
} else {
Log.d(TAG, task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
time: 1617695199510
Try this...
mDatabase.child("/server/time/Time").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
long time = dataSnapshot.getValue(Long.class);
Log.d(TAG, "Time :- " + time);
MyApplication.getInstance().setmServer(new server(time));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
hideProgressDialog();
}
});
The result in logcat is..
Time :- 1617695199510
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.