/** * Here, we will demonstrate the use of Firebase Realtime DB which syncs your data across different * devices that are accessing the same DB in realtime. */ publicclassRealtimeDatabaseActivityextendsAppCompatActivity {
// Connect with firebase mDatabase = FirebaseDatabase.getInstance(); // The documentation mentions that you do not need to add the URL if your location is // us-central1, but at times it does not work. If it does not work, then add the url of your // db in the getInstance() call. eg: getInstance("https://testfirebase-default-rtdb.firebaseio.com/")
// Update the score in realtime mDatabase.getReference().child("users").addChildEventListener( newChildEventListener() {
/** * This method resets the scores of both the players back to 0 on the DB as well as the app. * * @param view the button reference from the XML file. */ publicvoidresetUsers(View view) {
User user; user = newUser("user1", "0"); Task<Void> t1 = mDatabase.getReference().child("users").child(user.username).setValue(user);
user = newUser("user2", "0"); Task<Void> t2 = mDatabase.getReference().child("users").child(user.username).setValue(user);
if(!t1.isSuccessful() && !t2.isSuccessful()){ Toast.makeText(getApplicationContext(),"Unable to reset players!",Toast.LENGTH_SHORT).show(); } elseif(!t1.isSuccessful() && t2.isSuccessful()){ Toast.makeText(getApplicationContext(),"Unable to reset player1!",Toast.LENGTH_SHORT).show(); } elseif(t1.isSuccessful() && t2.isSuccessful()){ Toast.makeText(getApplicationContext(),"Unable to reset player2!",Toast.LENGTH_SHORT).show(); }
}
// Add data to firebase button publicvoiddoAddDataToDb(View view) { // Write a message to the database DatabaseReferencemyRef= mDatabase.getReference("message");
Task<Void> t = myRef.setValue("Hello, World!");
t.addOnCompleteListener(task -> { if(!t.isSuccessful()){ Toast.makeText(getApplicationContext() , "Failed to write value into firebase. " , Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext() , "Write Successful." , Toast.LENGTH_SHORT).show(); } });
// Read from the database by listening for a change to that item. myRef.addValueEventListener(newValueEventListener() { @Override publicvoidonDataChange(@NonNull DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. Stringvalue= dataSnapshot.getValue(String.class); Log.d(TAG, "Value is: " + value); TextViewtv= (TextView) findViewById(R.id.dataUpdateTextView); tv.setText(value); }
@Override publicvoidonCancelled(@NonNull DatabaseError error) { // Failed to read value Log.w(TAG, "Failed to read value.", error.toException()); Toast.makeText(getApplicationContext() , "Failed to write value into firebase. " , Toast.LENGTH_SHORT).show(); }
});
}
/** * This method represents adding 5 points to the score of the specified player. * * @param postRef a reference of the database * @param user String specifying whether it is user 1 or 2 */ privatevoidonAddScore(DatabaseReference postRef, String user) { postRef .child("users") .child(user) .runTransaction(newTransaction.Handler() { @NonNull @Override public Transaction.Result doTransaction(@NonNull MutableData mutableData) {
Useruser= mutableData.getValue(User.class);
if (user == null) { return Transaction.success(mutableData); }
/** * Displays the score using the DataSnapshot object by getting the "User" object corresponding * values from it. * * @param dataSnapshot Immutable copies of the data at a Firebase Database location. */ privatevoidshowScore(DataSnapshot dataSnapshot) { //Getting the user object corresponding value from the dataSnapshot Useruser= dataSnapshot.getValue(User.class);
if (dataSnapshot.getKey() != null) { //Appropriately updating the score of the user by querying on the name of the user. if (dataSnapshot.getKey().equalsIgnoreCase("user1")) { score_user1.setText(String.valueOf(user.score)); user1.setText(user.username); } else { score_user2.setText(String.valueOf(user.score)); user2.setText(user.username); } } }
// The documentation mentions that you do not need to add the URL if your location is // us-central1, but at times it does not work. If it does not work, then add the url of your // db in the getInstance() call. eg: getInstance("<https://testfirebase-default-rtdb.firebaseio.com/>")
publicvoidcreateNotificationChannel() { // This must be called early because it must be called before a notification is sent. // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequencename= getString(R.string.channel_name); Stringdescription= getString(R.string.channel_description); intimportance= NotificationManager.IMPORTANCE_DEFAULT; NotificationChannelchannel=newNotificationChannel(getString(R.string.channel_id), name, importance); channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManagernotificationManager= getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } }
publicvoidsendNotification(View view) {
// Prepare intent which is triggered if the // notification is selected Intentintent=newIntent(this, ReceiveNotificationActivity.class); PendingIntentpIntent= PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0); PendingIntentcallIntent= PendingIntent.getActivity(this, (int) System.currentTimeMillis(), newIntent(this, FakeCallActivity.class), 0);
// Build notification // Need to define a channel ID after Android Oreo StringchannelId= getString(R.string.channel_id); NotificationCompat.BuildernotifyBuild=newNotificationCompat.Builder(this, channelId) //"Notification icons must be entirely white." .setSmallIcon(R.drawable.foo) .setContentTitle("New mail from " + "test@test.com") .setContentText("Subject") .setPriority(NotificationCompat.PRIORITY_HIGH) // hide the notification after its selected .setAutoCancel(true) .addAction(R.drawable.foo, "Call", callIntent) .setContentIntent(pIntent);
NotificationManagerCompatnotificationManager= NotificationManagerCompat.from(this); // // notificationId is a unique int for each notification that you must define notificationManager.notify(0, notifyBuild.build());