I am trying to send notifications to some users that I have on my database on Firebase, I know that Firebase has a section related to notifications, but I just saw an example to how push notification directly from the Firebase website, I have an event in my app, when that event is created I want to send the notification to all users so basically this is the event:
public void createEventGame(View view){
Match match = new Match(userId,gameEventNameTxt.getText().toString(),dateMatch);
String key = myGameRef.push().getKey();
myGameRef.child(key).setValue(match);
/*if(radioMatchSelected){
}*/
if(radioEventSelected){
final HashMap<String,Boolean> matches = new HashMap<String,Boolean>();
matches.put(key,true);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
final String text = spinner.getSelectedItem().toString();
Log.d("sizebb",text);
myRef.child(userId).child("FriendLists").child(text).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long size = dataSnapshot.getChildrenCount();
Log.d("sizebb",String.valueOf(size));
for(DataSnapshot s: dataSnapshot.getChildren()){
friends.put(s.getKey(),false);
}
if(size < 10){
Snackbar snackbar = Snackbar
.make(findViewById(android.R.id.content), "You need to have atleast 10 friends in your group, go to your friendlist and add some friends!", Snackbar.LENGTH_LONG);
snackbar.show();
}
Event event = new Event(gameEventNameTxt.getText().toString(),hourWeek,userId,matches,friends,dayOfWeek);
myEventRef.child(event.getName()).setValue(event);
/*else{
friends.put(dataSnapshot.getKey(),true);
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now how can i deal with notifications, is there any good tutorial talking about it? I can't find it, or do I need to deal with notifications with the database on firebase directly?
Not clear about the question, will try my best.
So you can send firebase notifications through console to all the users. You can also group users based on topics they subscribed and also to single devices (You need a token to send individual devices). Firebase cloud messaging. Also, you can send notifications from your program logic.
Look at the various types of notifications that you can send here.
Another place to quick start with firebase is their github repo. Almost you can find a quick start project for everything. Firebase Github repo
Have all the friends you want to send the Notification to subscribe to a common topic.
When the event occurs, call the Firebase REST API and send the notification to this topic and all your users should get them. Notification tag or Data tag or both is upto your usecase. I prefer Data tag only so as to ensure that everything that happens stays in the code that i write and not system code.
What topic name you choose and which people subscribe is upto you. This should get you started.
Related
I'm new to Android studio. I was able to create login and auth for my app using firebase.
I'm now trying to create a submission form for the user to create and log all the fields in firebase. I would also need the ability as admin to approve the submission request and notify user by push notification or email. The email is one of the fields in the submission form.
Looking for some guidance.
Thanks
Use Firebase Realtime Database + Firebase Functions.
You can see examples here.
You'll need to use FirebaseDatabase for that, go through this to set things up-
https://firebase.google.com/docs/database/android/start/
So first of all, add a EditText fields (simplest way) for each entry you want in your xml such as emails, password, etc.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Email"/>
</EditText>
Next, in your java file, convert these entries to strings.
Create a DatabaseReference (Make sure you have included firebase database library in you app level build.gradle file) and point to the location where you want to store the form entries.
Create a HashMap in which you store id and entry of each field. Directly upload this map instead of uploading each and every field separately.
Don't forget to check that the entries aren't empty.
Somewhat like this-
//global variables in class
private EditText email;
private DatabaseReference mdatabase;
//inside onCreate() method
mdatabase=FirebaseDatabase.getInstance().getReference().child("Wherever you want to store this data");
email = (EditText) findViewById(R.id.emailf);
String mymail = email.getText().toString();
if(!TextUtils.isEmpty(myname)&&!TextUtils.isEmpty(mymail)&&!TextUtils.isEmpty(mypass))
{
//create a map
HashMap< String,String> hm =
new HashMap< String,String>();
hm.put("email", mymail);
hm.put("password", mypass);
hm.put("name", myname);
mdatabase.setValue(hm).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
//do whatever you want, your details have been uploaded to your database- mdatabase
}
}
});
}
Push Notifications can be implemented using Firebase Cloud Messaging service and node.js
You'll also need to learn about Firebase Functions, very necessary.
Begin here-
https://firebase.google.com/docs/cloud-messaging/
and here-
https://www.youtube.com/watch?v=BsCBCudx58g
and then here-
https://www.youtube.com/watch?v=2MYgZQjX7N0&list=PLk7v1Z2rk4hjxP_CHAhjXQN3zrcEhluF_
I hope this answered your question!
I am building a chatapp using firebase database. I need to show online users, how can I do that?
I already tried this
connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
} else {
}
}
#Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});
But I don't know how to use it, please help me.
To achieve this, you need to create a new category in your Firebase database called onlineUsers. Every time a user is connecting to your app, add him to this newly created category. Then you can query on that category to see the exact number of users like this:
int numberOfUsers = dataSnapshot.getChildrenCount();.
If you need to display a green dot for online members in a list of members, then the way in which you need to add these users in this new node, is to have the id as it's key and the value as a boolean. The default boolean value must be false, which means that the user is not logged in. Your new node should look like this:
userId1: true
userId2: false
userId3: true
Every time a user signs in, change the value of that user from false to true. To display them, just query your database accordingly to see which users have the value of true.
If clients have a server to work up against,
each client connection is reported to the server, which increments a coutner.
And for such increment server is notifying (e.g. using Firebase data notification message) all clients.
This is how all clients will have indication about how many are conencted at any given time.
(When a new user is logged in, server is sending data about current number of connections)
pretty straightforward question. im making an android app that uses firebase authentication for users to connect with email and password an also the firebase realtime database service.
i wanted to know if i can check through android studio how many people are currently connected to my database(through Firebase Authentication)
thanks in advance!
This is an old question but in case someone is searching for a solution, I've found some info on Firebase docs:
https://firebase.google.com/docs/firestore/solutions/presence
It's very simple. Every time a user is connecting to your app, add him in a Firebase category, named users. Then you can query on that category to see the exact number of users using the following line of code:
int numberOfUsers = dataSnapshot.getChildrenCount();
var database = firebase.database();
// connecting users
var connectionsRef = database.ref("/connections");
var connectedRef = database.ref(".info/connected");
// Number of online users is the number of objects in the presence list.
// When the client's connection state changes...
connectedRef.on("value", function(snap) {
// If they are connected..
if (snap.val()) {
// Add user to the connections list.
var con = connectionsRef.push(true);
// Remove user from the connection list when they disconnect.
con.onDisconnect().remove();
}
});
// When first loaded or when the connections list changes...
connectionsRef.on("value", function(snapshot) {
// Display the viewer count in the html.
// The number of online users is the number of children in the connections list.
console.log("numers of players are:"+ snapshot.numChildren());
$(".displayDiv").text(snapshot.numChildren());
I just started storing usertokens in my database for notification purposes. I have no problem storing and retrieving the data except with certain usertoken string values. But when I take a datasnapshot with a usertoken it returns null, only sometimes though.
My listener looks like this (just a regular listener):
udRef.addListenerForSingleValueEvent(new ValueEventListener () {
#Override
public void onDataChange(DataSnapshot datasnapshot) {
User user = datasnapshot.get value(User.class);
//do something with data here
//eg. Log.e("ERR", String.value Of(user));
//returns "null" for SOME users only, keep reading.
}
#Override
public void onCancelled (DatabaseError databaseError) { ... }
});
When a user creates an account, it automatically inserts a string token that looks like this:
"cL_AEuSZa1I:APA91bF9R-dDetqrSNMQMzAoHRmLOHXK2acK_zJLhFhZ5IhvNChPSx4P943GirVwsy5walc0RrvyGnMm49oLxNJ-uKsGRCELhJ-9kwnPmdHOyWJWz0Esm_Y0MB7BypNUuQ4qZQmoW5nO"
Tokens are used for push notifications using FCM. This is refreshed automatically as recommended by the FB guys. The token above isn't valid, in fact this very usertoken made my datasnapshot not work so I had to manually remove it! And yes, immediately I removed it I was able to capture the snapshot, it didn't return null anymore.
I do not know what I'm doing wrong, but when I look (with my eyes, not a script) at the usertokens in the database I can tell which ones will be troublesome. This is how:
All usertokens are too long, so Firebase's web console cuts them short like this "gftgvdgGhbgfc_fggg..."
All the troublesome tokens get cut also but without the 3 dots or closing quotes, they look like this "gftgvdgGhbgfc_fggg but when expanded they are normal like the working ones (length is same).
I have 30 users so I can easily go through them all :D
This is how my data looks (roughly):
"fhgfFghDfgghhfDDf" : {
"username" : "a_string_here"
"userPic" : "looong_string_link_to_fb_storage"
"usertoken" : "long_user_token_like the_one_in_question"
},...
Am I storing the tokens wrongly?, should I convert them to some other data type? Too many 'gotchas' in FB :(
Please note, I DO NOT have problems with anything else except the usertokens making my datasnapshot null, so any mistakes in the code are just typos (I typed this question from my phone referencing my laptop screen... don't ask)
first I apologize for my poor English. I'm just approaching to Parse.com and I'm developing a "multi-server" application that allows me to send notifications filtered by "server".
I tried two solutions but both have some issue all connected to the fact that when i start my Application i don't know which "server" the user will choose.
Idea 1 - Real Multi Server
I create manually n Parse.com servers, totally separated each other
I store all my servers keys in objects like [Name, AppID, clientKey]
My application lists the name attribute
The user choose his server
I start new Activity in which onCreate() I initialize Parse like:
String appID = getAppID();
String cKey = getKey();
Parse.initialize(this, appID, cKey);
ParseInstallation.getCurrentInstallation().saveInBackground();
(If he want to change server i simply clean my App data and re-initialize Parse with the new keys)
Everything works fine until I try to send a Push Notification when the the app is closed (not active and not in background) when I have a NullPointerException due to initialization of Parse not yet called.
Idea 2 - Simulated Multi Server
I create manually ONE Parse.com server
All tables have a new Column like (just as example) uniqueIdServer
I initialize Parse in Application like:
public class MyApplication extends Application {
#Override
public void onCreate() {
Parse.initialize(this, "ThisTimeIHaveJustOneAppIDIt'sEasy", "SameHere");
ParseInstallation.getCurrentInstallation().saveInBackground();
super.onCreate();
}}
I display my old list but this time is just [name, uniqueID]
The user choose his "server"
Now i can easy filter my data with my new column and i have no problem when my app is closed because Parse will call his initializer by his own
But i don't know how i can filter Push Notification just for some uniqueId
I tried using channels and than sending Push only at that channel:
List<String> channels = new ArrayList<>();
channels.add(getUniqueID());
ParseInstallation install = ParseInstallation.getCurrentInstallation();
install.put("channels", channels);
install.saveEventually();
But is always the same, i dont know at "Application time" what my user will choose so my getUniqueID() will bind "null" or similar and even worse i don't know how can i change channel (atm i can only if i uninstall my app)
Really thanks at all, any help will be really appreciated.
Using your idea 2, installations can be given custom attributes and queried exactly as any other objects. Moreover, pushes can be made with an installation query. See "advanced targeting" in the docs.
Minimally, you can say something like this:
var query = new Parse.Query(Parse.Installation);
query.equalTo('uniqueIdServer', 'serverId123');
var data = { alert: "Ciao users of serverId123!" }
Parse.Push.send({ where: query, data: data }).then(function() {
// this code runs after the push has been sent to APN
}, function(error) {
// this code runs in case of an error
});