Get notifcation when add new data to firebase realtime database - java

when open the application i want to get notification if new data added to firebase realtime database .
but whan i open the app i got notifcation every time i open the it.
what should i do
this is my code.
cam_firebase.child("Detection").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NotNull DataSnapshot dataSnapshot, String s) {
double longt = dataSnapshot.child("longt").getValue(Double.class);
double lat = dataSnapshot.child("lat").getValue(Double.class);
notify_me();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
}
});

Related

Firebase Android Database Query (Read Data)

I am trying to fetch the data from the firebase database where the valueNum is the contact number with +91. I have shown the same in the screenshot attached but when I am running the code. It gave me a list of all the users even from different valueNum. However, If I pass the incorrect value, giving me the same result i.e. no error.database screen capture
private void funcDatabaseActivity(String valueNum) {
databaseReference.child("users").child("registered-user/" + valueNum).addChildEventListener
(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()) {
UserData data = dataSnapshot.getValue(UserData.class);
Toast.makeText(ContactsActivity.this, "Data Exists - " + data.getDisplayName(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ContactsActivity.this, "Data Not Exists", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
As shown in the screenshot of the database, you are performing an incorrect sequence. I have modified this for you in the answer.
You must take a logical path to access specific information. Also, you can read about ChildEventListener, its uses, and the difference between it and addValueEventListener.
private void funcDatabaseActivity(String valueNum) {
databaseReference= FirebaseDatabase.getInstance().getReference("database-find-me");
databaseReference.child("users").child("registered-user").child(valueNum).addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Type here as you like
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(this, "check your internet", Toast.LENGTH_SHORT).show();
}
});
}

how to fetch data in range using timestamp - Firebase, Android, Real-time Database

I am using firebase real-time database to store and retrieve data but for some reason, I am unable to achieve what I want.
I want to get 20 records at a time on swipe refresh layout.
My data looks like:
Initially, I load 50 records:
chat.limitToLast(default_num_of_messages).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String user_id = map.get("user_id").toString();
String message = map.get("message").toString();
String timestamp = map.get("timestamp").toString();
Log.d("MAP", map.toString());
ChatMessage chat_message = new ChatMessage();
chat_message.setUser_id(user_id);
chat_message.setMessage(message);
chat_message.setTimestamp(Long.parseLong(timestamp));
Log.d("CHAT MSG", chat_message.toString());
if(Integer.parseInt(user_id) == Utils.getInstance().getLoggedInUser().getId()) {
addMessageBox(chat_message, 1);
}
else{
addMessageBox(chat_message, 2);
}
}
after these on refresh, I want to load 20 more. I am trying to do something like these. but it does not seem to return.
#Override
public void onRefresh() {
if(refresh_toggle) {
swipe_view.setRefreshing(true);
Log.d("CHAT", "REFRESHED!!!");
//reload new data
chat.orderByChild("timestamp").endAt(10).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String user_id = map.get("user_id").toString();
String message = map.get("message").toString();
String timestamp = map.get("timestamp").toString();
Log.d("CHATS", map.toString());
ChatMessage chat_message = new ChatMessage();
chat_message.setUser_id(user_id);
chat_message.setMessage(message);
chat_message.setTimestamp(Long.parseLong(timestamp));
swipe_view.setRefreshing(false);
if(Integer.parseInt(user_id) == Utils.getInstance().getLoggedInUser().getId()) {
addMessageBox(chat_message, 1);
}
else{
addMessageBox(chat_message, 2);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
}
As you can see I am trying to orderByChild "timestamp" and then tried different combination of startAt(), endAt() but nothing seem to work.
Try this:
int number_item_load = 10; //changed number if you want
public void loadMore(int offset, String theLastValue) {
// theLastValue: depend on your orderByChild() 's value
mDatabase = FirebaseDatabase.getInstance().getReference().child(Utils.FB_ROOT);
mEventListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (isAlreadyAttach()) {
// Get your item and callback to view and insert to listView
}
} ...
};
mDatabase.orderByChild("yourvalue").startAt(theLastValue).limitToFirst(number_item_load ).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// TODO Finished loaded number_item_load item
OnLoadedFinish(); //
mDatabase.removeEventListener(mEventListener); // Remove listener after load
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDatabase.orderByChild("yourvalue").startAt(theLastValue).limitToFirst(number_item_load ).addChildEventListener(mEventListener);
}
It worked perfectly in my case. Goodluck

Firebase Database strange ordering

I have this "chat-system" that I made with Firebase Database.
To retrieve the messages in the Room I do a Query with an orderByChild(timestamp) then reverse the order so I can get the "newest" Last (Because I start reading from the Bottom).
messageList = new ArrayList<>();
final Query query = chatRef_1.orderByChild("
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
messageList.add(dataSnapshot.getValue(ChatMessage.class));
updateRecyclerView();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
messageList.remove(dataSnapshot.getValue(ChatMessage.class));
updateRecyclerView();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
But then I get this result
This only happens with ChildEventListener
The TimeStamp is done by the server
Does anyone have an Idea of what this might be?
UPDATE
Here's the database Structure
Box »» Object (Message)
Green »» MessageID
Blue »» RoomID

Retrieving random key from Firebase database

How should I retrieve random key from Firebase realtime database that are stored in list?
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("inspirational");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String randomkey=dataSnapshot.getkey();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Use ChildEventListener since this is a list, first get the reference of the database. .child("inspirational") it means we are querying on that location.
Then inside onChildAdded(DataSnapshot dataSnapshot, String s) retrieve your data.

Android - Traversing firebase Database using snapshot

This is my database in firebase.
This is my java code for traversing database.
mref = new Firebase("https://social-axxxxxcf.firebaseio.com/user");
mref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
String email=userSnapshot.child("email").getValue().toString();
String urL=userSnapshot.child("url").getKey().toString();
Log.e("Datas= ",email+" " +url);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("TAG= ",firebaseError.getMessage());
}
});
My problem is when i run this code my app getting crash and even error in log is not showing.
Can anyone help me please.
Since you're using ChildEventListener on /user, your onChildAdded will get called for every node under/user. This means you don't need t loop over dataSnapshot.getChildren():
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String email=dataSnapshot.child("email").getValue(String.classs);
String urL=dataSnapshot.child("url").getValue(String.class);
Log.e("email="+email+" url="+url);
}
Check the following link it's the working example to implement firebase with android.
link

Categories