Getting error in Firebase one to one chat app Notifications - android

I have made a one to one chat app and I have implemented chat notifications but when I am sending notifications from the user app to the doctor app but my doctor app crashes as soon as I am clicking on the chat notification
This is my Java class where I am handling the notification if my app is in foreground so this class will handle notifications so now in this class I am calling firebase database and taking some data from there and passing that data as an extra data with the resulting intent but when that resulting intent directs the app to the particular chat view that database data is not there
This is the Log of my app
E/MyFirebaseMessaging: From:408315985482
07-05 16:19:33.803 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: in between Firebase and auth
07-05 16:19:33.805 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: Message data payload: {idRe, username=komal , message=hi}
07-05 16:19:33.805 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: app in background
07-05 16:19:33.813 4399-6278/com.tech.pritz.bemoprovider E/MyFirebaseMessaging: image not found
07-05 16:19:33.825 4399-6278/com.tech.pritz.bemoprovider D/NotificationUtil: New Message
D/MyFirebaseMessaging: Entered into the database
07-05 16:19:34.359 4399-4399/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: HKNi1sezUpbwJSeEGos44FtfUw43
You can see here it is showing entered in the database also and it is getting that data also but when I pass it as an intent it is not found in another activity.
Crash log
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'java.lang.String
com.tech.pritz.bemoprovider.model.Provider.getId()' on a null object
reference at
com.tech.pritz.bemoprovider.bemo.ChatView.ini(ChatView.java:‌​350) at
com.tech.pritz.bemoprovider.bemo.ChatView.onCreate(ChatView.‌​java:150)
public class MyFirebaseMessaging extends FirebaseMessagingService
{
private static final String TAG=MyFirebaseMessaging.class.getSimpleName();
private NotificationUtil notificationUtil;
private DatabaseReference pathFirebase;
private FirebaseAuth auth;
private Provider mprovider;
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
Log.e(TAG,"From:"+ remoteMessage.getFrom());
pathFirebase = FirebaseDatabase.getInstance().getReference();
Log.d(TAG,"in between Firebase and auth");
auth = FirebaseAuth.getInstance();
if(remoteMessage ==null )
{
return;
}
//check if message contains a notification payload
if(remoteMessage.getNotification()!=null)
{
String tittle = remoteMessage.getNotification().getTitle();
Log.e(TAG,"Notification Body:" + remoteMessage.getNotification().getBody());
handleNotification(remoteMessage.getNotification().getBody(),tittle,null, mprovider);
}
//checks to see if message contains a data payload
if(remoteMessage.getData().size() > 0)
{
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
String imageUrl = remoteMessage.getData().get("image");
// String message = remoteMessage.getData().get("message");
// String title = remoteMessage.getData().get("title");
// String name = remoteMessage.getData().get("username");
String message= remoteMessage.getData().get("message");
String name= remoteMessage.getData().get("username");
String title= "New Message";
String iduser= remoteMessage.getData().get("iduser");
String email= remoteMessage.getData().get("email");
String gcm_id= remoteMessage.getData().get("idGCM");
String conversation_id=remoteMessage.getData().get("conversation_id");
Log.d(TAG,"app in background");
pathFirebase.child("users").child(auth.getCurrentUser().getUid())
.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG,"Entered into the database");
mprovider = dataSnapshot.getValue(Provider.class);
UserDataHolder.getInstance().setmName(mprovider.getName());
// Intent intent = new Intent(MyFirebaseMessaging.this, ListPatients.class);
mprovider.setId(auth.getCurrentUser().getUid());
UserDataHolder.getInstance().setmUserId(mprovider.getId());
// intent.putExtra("user", provider);
//startActivity(intent);
//finish();
Log.d(TAG,mprovider.getId());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MyFirebaseMessaging.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
// Log.d(TAG,mprovider.getId());
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(getApplicationContext(),ChatView.class);
resultIntent.putExtra("user_id", iduser);
resultIntent.putExtra("email", email);
resultIntent.putExtra("User_display_name",name);
resultIntent.putExtra("user_gcm_id",gcm_id);
resultIntent.putExtra("conversation_id",conversation_id);
// resultIntent.putExtra("providerLocal",mprovider);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// resultIntent.putExtra("message", message);
// check for image attachment
if (TextUtils.isEmpty(imageUrl))
{
Log.e(TAG,"image not found");
showNotificationMessage(getApplicationContext(), title, message,name,resultIntent,mprovider);
}
else
{
// image is present, show notification with image
Log.e(TAG,"image found");
showNotificationMessageWithBigImage(getApplicationContext(), title, message, resultIntent, imageUrl);
}
}
}
private void handleNotification(String message,String title,String name,Provider provider)
{
if(!NotificationUtil.isAppInBackground(getApplicationContext()))
{
Intent resultIntent = new Intent(getApplicationContext(), ChatView.class);
showNotificationMessage(getApplicationContext(), title, message,null,resultIntent, provider);
}
else
{
Intent resultIntent = new Intent(getApplicationContext(), ChatView.class);
showNotificationMessage(getApplicationContext(), title, message,null,resultIntent, mprovider);
}
}
private void showNotificationMessageWithBigImage(Context applicationContext, String title, String message, Intent resultIntent, String imageUrl)
{
notificationUtil = new NotificationUtil(applicationContext);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtil.showNotificationMessage(title, message,null,resultIntent,imageUrl);
}
private void showNotificationMessage(Context applicationContext, String title, String message,String name, Intent resultIntent,Provider mprovider)
{
// Log.d(TAG,mprovider.getId());
notificationUtil = new NotificationUtil(applicationContext);
resultIntent.putExtra("providerLocal",mprovider);
// resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtil.showNotificationMessage(title, message,name,resultIntent);
}
}

the problem is in this line :
UserDataHolder.getInstance().setmUserId(mprovider.getId());
the mprovider object is null

Related

Send FCM to user subscribed to a topic programmatically

I am creating a BloodBank app in which, when the user requests for the blood, It takes the requested Blood group and search the same in the database. It displays list of all the users who can donate to that blood group.
In the list, I have already implemented an option to message and call the user. Additionally, I want the App to send a notification to all users who have the same blood group.
For achieving this I have subscribed the user to a topic at successful login and sent him a notification but I have done this through the console.
What I want to achieve is, as a user requests the blood and while showing him the list of all users who can donate, App should also send a notification to all the users who have subscribed to that topic.
So is there any possible way I can programmatically send FCM to all the users subscribed to the same topic.
Here I'm subscribing user to a topic at successful Login:
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
topicSubscription();
} else {
progressDialog.dismiss();
String exception = task.getException().getMessage();
HelperClass.showSnakbarMsg(rootView, exception);
}
}
});
}
private void topicSubscription() {
FirebaseMessaging.getInstance().subscribeToTopic("Blood")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String msg = getString(R.string.msg_subscribed);
if (!task.isSuccessful()) {
msg = getString(R.string.msg_subscribe_failed);
} else {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
Log.d("log", msg);
Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
This is my Firebase messaging class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
I have read about it and many have said to hit an API for this to send FCM programmatically. But I am creating the whole app in firebase so my DataBase is also in firebase and as my database is in firebase I can't use API for one notification only like I have to manage some table in DB for that notification and for only one table I have to manage a separate DB.
So is there any way that I can send FCM programmatically to all users who have subscribed to the same topic, on successful loading of the donor list which shows the user who can donate to the requested blood group.
Thanks
You can directly send push notification directly from android, to all the devices subscribed to the topic, check out the following link how to send msgs directly from android, but in this example user is sending message one to one, to send fcm message to user subscribed to a topic, you need to change the message format as specified by fcm documentation
User App
private void latLngNotification() {
Location loc1 = new Location("");
loc1.setLatitude(Double.parseDouble(userLat));
//loc1.setLongitude();
Location loc2 = new Location("");
loc2.setLatitude(Double.parseDouble(attendanceLat));
//loc2.setLongitude();
float distanceInMeters = loc1.distanceTo(loc2);
if (distanceInMeters > 50) {
//Toast.makeText(this, "distance: " + distanceInMeters, Toast.LENGTH_SHORT).show();
sendNotification();
} else {
//Toast.makeText(this, "distance: " + distanceInMeters, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "You are in home...", Toast.LENGTH_SHORT).show();
}
}
private void sendNotification() {
String TOPIC = "/topics/admin_app"; //topic has to match what the receiver subscribed to
JSONObject notification = new JSONObject();
JSONObject notifcationBody = new JSONObject();
String title = "Quarantine outside";
String message = mobileno + " User is out of his area";
try {
notifcationBody.put("title", title);
notifcationBody.put("message", message);
notification.put("to", TOPIC);
notification.put("priority", "high");
notification.put("data", notifcationBody);
} catch (JSONException e) {
Log.e(TAG, "onCreate: " + e.getMessage());
}
Notification(notification);
}
private void Notification(JSONObject notification) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", notification,
response -> Log.i(TAG, "onResponse: " + response.toString()),
error -> {
Toast.makeText(GetLocationActivity.this, "Request error", Toast.LENGTH_LONG).show();
Log.i(TAG, "onErrorResponse: Didn't work");
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Authorization", "key=AAAAwxBqu5A:APA91bERpf-1rh02jLciILt1rsLv7HRrFVulMTEAJXJ5l_JGrSHf96qXvLQV0bIROob9e3xLK4VN8tWo-zBPUL39HjxyW4MsX5nKW_NiQlZGgLDCySVwHXADlg16mpLUjgASj--bk-_W");
params.put("Content-Type", "application/json");
return params;
}
};
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
Admin App
FirebaseMessaging.getInstance().subscribeToTopic("admin_app");
Intent intent = getIntent();
if (intent != null) {
String userPhone = intent.getStringExtra("message");
//Toast.makeText(this, userPhone, Toast.LENGTH_SHORT).show();
message_txt.setVisibility(View.VISIBLE);
message_txt.setText(userPhone);
} else {
message_txt.setVisibility(View.GONE);
//Toast.makeText(this, "no data", Toast.LENGTH_SHORT).show();
}

Sending Notification from android to other android devices

I am always getting an error on sending notification from android device in logcat I have tried so many times but nothing getting:
{"multicast_id":5162718122421221171,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
Here is my android code for sending message I am sending userABC topic in the topic section.
public void SendNotification(String Title, String Message){
NOTIFICATION_TITLE = Title;
NOTIFICATION_MESSAGE = Message;
JSONObject notification = new JSONObject();
JSONObject notifcationBody = new JSONObject();
try {
notifcationBody.put("title", NOTIFICATION_TITLE);
notifcationBody.put("message", NOTIFICATION_MESSAGE);
notification.put("to", TOPIC);
notification.put("data", notifcationBody);
} catch (JSONException e) {
Log.e(TAG, "onCreate: " + e.getMessage() );
}
sendNotification(notification);
}
private void sendNotification(JSONObject notification) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse: " + response.toString());
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Request error", Toast.LENGTH_LONG).show();
Log.i(TAG, "onErrorResponse: Didn't work");
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Authorization", serverKey);
params.put("Content-Type", contentType);
return params;
}
};
MySingleton.getInstance(getActivity().getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
Here is my FirebaseInstanceIDService.java class
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "mFirebaseIIDService";
private static final String SUBSCRIBE_TO = "userABC";
#Override
public void onTokenRefresh() {
/*
This method is invoked whenever the token refreshes
OPTIONAL: If you want to send messages to this application instance
or manage this apps subscriptions on the server side,
you can send this token to your server.
*/
String token = FirebaseInstanceId.getInstance().getToken();
// Once the token is generated, subscribe to topic with the userId
FirebaseMessaging.getInstance().subscribeToTopic(SUBSCRIBE_TO);
Log.i(TAG, "onTokenRefresh completed with token: " + token);
sendRegistrationToServer(token);
}
private void sendRegistrationToServer(String token) {
// send token to web service ??
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-data/IDs");
// then store your token ID
ref.push().setValue(token);
}
}
Here is my FirebaseMessagingService.java class
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private final String ADMIN_CHANNEL_ID ="admin_channel";
#Override
public void onNewToken(String token) {
Log.d("TAG", "Refreshed token: " + token);
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d("THIS", "Refreshed token: " + refreshedToken);
FirebaseMessaging.getInstance().subscribeToTopic("userABC");
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
// send token to web service ??
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-data/IDs");
// then store your token ID
ref.push().setValue(token);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
final Intent intent = new Intent(this, MainActivity.class);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int notificationID = new Random().nextInt(3000);
/*
Apps targeting SDK 26 or above (Android O) must implement notification channels and add its notifications
to at least one of them. Therefore, confirm if version is Oreo or higher, then setup notification channel
*/
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupChannels(notificationManager);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this , 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(largeIcon)
.setContentTitle(remoteMessage.getData().get("title"))
.setContentText(remoteMessage.getData().get("message"))
.setAutoCancel(true)
.setSound(notificationSoundUri)
.setContentIntent(pendingIntent);
//Set notification color to match your app color template
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
notificationBuilder.setColor(getResources().getColor(R.color.colorPrimaryDark));
}
notificationManager.notify(notificationID, notificationBuilder.build());
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(NotificationManager notificationManager){
CharSequence adminChannelName = "New notification";
String adminChannelDescription = "Device to devie notification";
NotificationChannel adminChannel;
adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_HIGH);
adminChannel.setDescription(adminChannelDescription);
adminChannel.enableLights(true);
adminChannel.setLightColor(Color.RED);
adminChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(adminChannel);
}
}
}
FirebaseInstanceIdService is deprecated now.
So you can change your registration logic as below
FcmRegistrationManager.java
public class FcmRegistrationManager {
private static final String TAG = "FcmRegistrationManager"
/*This is async call*/
public void registerWithFcm(){
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
Log.d(TAG, msg);
sendRegistrationToServer(token)
}
});
}
private void sendRegistrationToServer(String token) {
// send token to web service ??
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-data/IDs");
// then store your token ID
ref.push().setValue(token);
}
}
No change for sendNotification() and FirebaseMessagingService class.
More reference : https://firebase.google.com/docs/cloud-messaging/android/client
Let me still not working, I will share you working code.

setValue() for Firebase data update causes other fields in updated object to return null in onChildAdded in childEventListener

I have a list of Firebase message objects, each of which may be updated before an activity is opened, at which point a Firebase ChildEventListener() fires off (children are handled in onChildAdded()).
The update uses a setValue() on the status field:
database.getReference("Messages").child(roomID).child(msgID).child("status").setValue("delivered");
The ChildEventListener() fires off fine for all children when the activity is opened. However, for those children (messages) that had their status' updated before hand, they return null for all fields except the status field.
In the Firebase database, all fields are as they should be (non-null), so there is nothing wrong with the data.
Upon exiting the activity and re-entering, all children are returned in the ChildEventListener() as they should be (no more null data returned).
In short, two ChildEventListener() calls are required to return all the data for a child after a setValue() is run on that child.
More code and context can be provided if required. Let me know.
Edit 1: here is the listener: (it is in onResume())
newMessageListner = myMessageRoomRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, String previousChildName) {
if (dataSnapshot.exists()) {
String messageKey = dataSnapshot.getKey();
Message messageClass = dataSnapshot.getValue(Message.class);
String messageUserID = messageClass.getUserId();
Log.d(TAG, "Message Key: " + messageKey);
Log.d(TAG, "Message Status: " + messageClass.getStatus());
Log.d(TAG, "Message User ID: " + messageUserID);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Edit 2: I call the getValue() from sendNotification() in my FirebaseMessagingService
private void sendNotification(RemoteMessage remoteMessage) {
//Intent intent = new Intent(this, StudentChatActivity.class);
String clickAction = remoteMessage.getData().get("click_action");
Intent intent = new Intent(clickAction);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
String roomID = remoteMessage.getData().get("ROOMID");
String origin = remoteMessage.getData().get("ORIGIN");
String msgID = remoteMessage.getData().get("MSGID");
Log.d(TAG, "Message data payload, roomID: " + roomID);
database.getReference("Messages").child(roomID).child(msgID).child("status").setValue("delivered");
intent.putExtra("ROOMID", roomID);
intent.putExtra("USERID", UserID);
intent.putExtra("USERNAME", UserName);
intent.putExtra("ORIGIN", origin);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.received_message);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.small_pickle)
.setContentTitle("FCM Message")
.setContentText(remoteMessage.getData().get("body"))
.setPriority(1)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

Firebase Cloud Messaging FCM Send Notification Message Android

I have two apps that use FCM, Client and Worker app. Client is sending the message:
String jsonLatLng = new Gson().toJson(new LatLng(Common.placeLatLng.latitude, Common.placeLatLng.longitude));
String clientToken = FirebaseInstanceId.getInstance().getToken();
Notification notification = new Notification(clientToken, jsonLatLng);
Sender content = new Sender(tokenId, notification);
mFCMService.sendMessage(content)
.enqueue(new Callback<FCMResponse>() {
#Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
if(response.body().success == 1) {
Toast.makeText(HomeActivity.this, "Request sent.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HomeActivity.this, "Request not sent.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<FCMResponse> call, Throwable t) {
}
});
Wherein Notification.java is
public class Notification {
public String title;
public String body;
...
}
Sender.java is
public class Sender {
public String to;
public Notification notification;
...
}
And with the Worker app, it receives:
public class MyFirebaseMessaging extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Convert lat lng
LatLng clientLocation = new Gson().fromJson(remoteMessage.getNotification().getBody(), LatLng.class);
Intent intent = new Intent(getBaseContext(), NotificationActivity.class);
intent.putExtra("lat", clientLocation.latitude);
intent.putExtra("lng", clientLocation.longitude);
intent.putExtra("client", remoteMessage.getNotification().getTitle());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
These codes work perfectly fine, however, I need to add more details, specifically, I want to send data from 2 String variables, serviceFee & serviceType over to the Worker app. I tried modifying the body of the Notification wherein I created a class called Body with three variables (jsonLatLng, serviceFee, serviceType), but I can't figure out how the worker will be able to get the data of Body or if that's even possible. Please help. Thank you! :)

Android - Display FCM notification message in Listview onClicking Notification

I have successfully sent Firebase notifications using my own server to Android app and I am listing the messages in a ListView in a new activity by clicking the notification. My issue is if I click on one particular notification, all unread notification messages are getting displayed in ListView.
FirebaseMessageservice.java:
private void sendPushNotification(JSONObject json) {
//optionally we can display the json into log
Log.e(TAG, "Notification JSON " + json.toString());
try {
//getting the json data
JSONObject data = json.getJSONObject("data");
//parsing json data
String title = data.getString("title");
String message = data.getString("message");
String imageUrl = data.getString("image");
list.add(message);
Collections.reverse(list);
System.out.println(list);
MyNotificationManager mNotificationManager = new MyNotificationManager(getApplicationContext());
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
//if there is no image
if(imageUrl.equals("null")){
//displaying small notification
mNotificationManager.showSmallNotification(title, message, intent);
}else{
//if there is an image
//displaying a big notification
mNotificationManager.showBigNotification(title, message, imageUrl, intent);
}
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ListView listView = (ListView) findViewById(R.id.notification_list);
adapter = new ListViewAdapter(this, list);
listView.setAdapter(adapter);
}
}
Output Screens
If i click on Hello Mom, It moves to next activity with listview but with both messages are getting displayed "1. Mom 2. Dad"

Categories

Resources