i try to make android app by retrieve temperature and hum data from firebase
json
how to show the data to textview android?
and how to show the latest inserted data from firebase.
thanks
UPDATE
i try this
code
can you give me an example to show the data to android please?
thanks for your help
What you need here is a ValueEventListener. In the fragment/activity that displays your TextView, you can add a ValueEventListener to a firebase reference like this:
// Get reference to firebase location where the data is stored
final Firebase databaseRef = new Firebase(Constants.FIREBASE_URL);
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(LOG_TAG,"ValueEventListener:onDataChange: " + "Data has changed");
// Get data
String temperatureData = (String) dataSnapshot.getValue();
// Update UI elements here...
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e(LOG_TAG,"ValueEventListener:onCancelled: " + firebaseError.getMessage());
}
});
Whenever the data at the specified location changes, the onDataChange() callback is triggered, so the UI is always up-to-date. Very powerful.
As someone new to Firebase myself, I can recommend this Udacity course : https://www.udacity.com/course/firebase-essentials-for-android--ud009
Related
I am fetching JSON array of user ids from a server (not Firebase server).
I also store images of each user in Firebase storage. I have a dataset of Users, that contain user id and user image url. The JSON response is constantly updating, so every call I receive new response from the server with new list of user ids. The only solution I came up with, is to:
Clear dataset > Loop through the JSON Array to add all users to the empty dataset > notify dataset changed.
The problem with this is that it's not efficient: I notify data set changed on each iteration, and also since I clear the dataset every new response (from the remote server), the list refreshes, instead of simply adding / removing the necessary users.
This is how the code looks:
#Override
public void onResponse(JSONArray response) { // the JSON ARRAY response of user ids ["uid1", "uid334", "uid1123"]
myDataset.clear(); // clear dataset to prevent duplicates
for (int i = 0; i < response.length(); i++) {
try {
String userKey = response.get(i).toString(); // the currently iterated user id
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userKeyRef = rootRef.child("users").child(userKey); // reference to currently iterated user
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
myDataset.add(new User(dataSnapshot.getKey(), dataSnapshot.child("imageUrl").getValue().toString())); //add new user: id and image url
mAdapter.notifyDataSetChanged(); // notify data set changed after adding each user (Not very efficient, huh?)
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
userKeyRef.addListenerForSingleValueEvent(listener);
}
catch (JSONException e) { Log.d(TAG, "message " + e); }
}
You might be interested in DiffUtil.
It uses an efficient algorithm to calculate the difference between your lists. And the cherry on the top is that this can be run on a background thread.
It is an alternative to notifyDataSetChanged() and is sort of an industry standard way for updating your RecyclerView
You can use Firebase Cloud functions.Pass the JSON Array to cloud function and retrieve the updated dataset in one go and notify the recycle view Here is link
As I have saved coordinates in firebase real time database of all the authenticated user. Now I want to retrieve all the coordinates which is on firebase database to show on map
like multiple marker on single map
Here is my code for sending location to firebase
public void onLocationChanged(Location location) {
FirebaseUser user = fb.getCurrentUser();
databaseReference.child("Location").child(user.getUid()).child("parth1234").setValue(location.getLatitude() + " , " + location.getLongitude());
}
Now how can I retrieve these location into map activity
as have created map activity, but I don't know anything related to this
please help with some code
Thanks in advance
I am beginner in android studio
is the saving location into firebase method which i have used is correct method ??
You are setting in correct way.To retrieve data you need to attach a Value Listener(for more info https://firebase.google.com/docs/database/android/read-and-writeDo the following:
FirebaseDatabase.getInstance().getReference("Location").child((user.getUid()).child("parth1234").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Now you can do whatever you want with that location value
//dataSnapshot.getValue(String.class)
//I printed it in the code below for you
System.out.println(dataSnapshot.getValue(String.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Handle the error
}
});
I have a firebase database from which I save and retrieve data from, to and from. I know how datasnapshot works inside an addValueEventListener. The problem is that this is only called or triggered when the firebase database detects change in its data. I only want to access data and read it to be able to store it in an arraylist or the same thing.
I have a code like this:
public void foo(){
DatabaseReference x= FirebaseDatabase.getInstance().getReference().child("x");
reservations.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userID = client.getId();
for(DataSnapshot snap : dataSnapshot.getChildren()){
if(snap.child("someId").equals(someId)) number++;
if(snap.child("userID").getValue().equals(client.getId())){
isAlreadyReserved = true; // if user has already reserved the item
alreadyReserved();
break;
}
Log.e("isAlreadyReserved: ", isAlreadyReserved+"");
numberOfReservations++;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(isAlreadyReserved) {
alreadyReserved();
}
else if(number == numberOfCopies){
// material is no longer available
OtherActivity.showMaterialUnavailable();
}
else{
Reservation reservation = new Reservation();
reservation.setBookId(this.bookId);
reservation.setResID((numberOfReservations+1)+"");
reservation.setUserID(client.getId());
String key = reservations.push().getKey();
reservations.child(key).setValue(reservation);
Log.e("Reservations: ", "reserve successful");
AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
builder.setTitle(R.string.reservationSuccess_title)
.setMessage(R.string.reservationSuccess_body);
AlertDialog dialog = builder.create();
dialog.show();
}
}
You can see that inside onDataChange I only count materials and set some flags, which I can supposedly do outside the ValueEventListener.
But I notice that this is faulty because onDataChange is called only when writing to the Firebase database occurs. Which should not be the case.
What can I do to loop through the values inside the DatabaseReference x without calling onDataChange, or without using DataSnapshot?
You cannot loop inside a DatabaseReference without using a listener. When we are talking about Firebase, we are talking only about listeners. So in order to get those values, you need to use a listener and than get the data out from the dataSnapshot.
What i think your problem is in your case, is that onDataChange method is called in an asynchronously way. This means that everything you are doing outsite this method is actually executed before onDataChange method has been called. So in order to understand what is actually going on, please see this post and this post. Reading this posts, will teach you how to query data in Firebase and how to retrieve data from Firebase asynchronously.
Hope it helps.
In order to get the values of DatabaseReference x, you should use addListenerForSingleValueEvent
x.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
//do something
}
#Override
public void onCancelled(DatabaseError databaseError)
{
//do something
}
});
as mentioned in the firebase documentation:
public void addListenerForSingleValueEvent (ValueEventListener
listener)
Add a listener for a single change in the
data at this location. This listener will be triggered once with the
value of the data at the location.
I have an addValueEventListener which listens to any value changes in Firebase Realtime Database. In online mode, everything is working fine.
But in offline mode, device is offline and my Web Server has done multiple transactions on Firebase Realtime Database on same value for which I put the listener from Android. After the device comes online, it will only listen for the last transaction and skipping the other transactions done in between.
PFB reference link. PFB code which i have done so far:
FirebaseDatabase.getInstance().setPersistenceEnabled(false);
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference("mykey");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, Object> key_Value = (HashMap<String, Object>) dataSnapshot.getValue();
for (String key : key_Value.keySet()) {
System.out.println("firebase key is "+key);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("feroz ", "Failed to read value.", error.toException());
}
});
}
The Firebase Realtime Database stores information came back from an inquiry for use when disconnected. For questions developed while disconnected, the Firebase Realtime Database keeps on working for already stacked information. On the off chance that the asked for information hasn't stacked, the Firebase Realtime Database loads information from the nearby reserve. When we return online our information will stack and mirror the inquiry.
For instance, here we have a bit of code in our application that questions for the last four things in our Firebase Realtime Database of scores
DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("scores");
scoresRef.orderByValue().limitToLast(4).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
System.out.println("The " + snapshot.getKey() + " dinosaur's score is " + snapshot.getValue());
}
});
I have been looking for a way to get one child object's data in Android Firebase.
I have found things like Firebase retrieve child Android. All the solutions are suggesting using a "ChildEventListener", however I need to get this data at this moment, not when it is moved, deleted, updated, etcetera.
My data is kept in https://.firebaseio.com/users//creation as a string. I figure there must be some simple way to access that without needing to do too much, because if I copy the exact URL to my browser, I can see the: 'creation: "2015/05/31 21:33:55"' right there in my "Firebase Forge Dashboard".
How can I access this without a listener?
Firebase listeners fire for both the initial data and any changes.
If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.
This is covered in Firebase's quickstart guide for Android. The relevant code and quote:
FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue()); //prints "Do you have data? You'll love Firebase."
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In the example above, the value event will fire once for the initial state of the data, and then again every time the value of that data changes.
Please spend a few moments to go through that quick start. It shouldn't take more than 15 minutes and it will save you from a lot of head scratching and questions. The Firebase Android Guide is probably a good next destination, for this question specifically: https://firebase.google.com/docs/database/android/read-and-write
You don't directly read a value. You can set it with .setValue(), but there is no .getValue() on the reference object.
You have to use a listener. If you just want to read the value once, you use ref.addListenerForSingleValueEvent().
Example:
Firebase ref = new Firebase("YOUR-URL-HERE/PATH/TO/YOUR/STUFF");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = (String) dataSnapshot.getValue();
// do your stuff here with value
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Source: https://www.firebase.com/docs/android/guide/retrieving-data.html#section-reading-once
just fetch specific node data and its working perfect for me
mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.e(TAG, "======="+postSnapshot.child("email").getValue());
Log.e(TAG, "======="+postSnapshot.child("name").getValue());
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
I store my data this way:
accountsTable ->
key1 -> account1
key2 -> account2
in order to get object data:
accountsDb = mDatabase.child("accountsTable");
accountsDb.child("some key").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
try{
Account account = snapshot.getChildren().iterator().next()
.getValue(Account.class);
} catch (Throwable e) {
MyLogger.error(this, "onCreate eror", e);
}
}
#Override public void onCancelled(DatabaseError error) { }
});