-1

I'm trying to pass image inside the FireBase Notification but it is showing me error for parsing the json object bellow is the log cat that shows the errorenter image description here

this is the json that send the data from server

{"to":"dJ4ege8LbI8:APA91bGqGQyIEBn2TsSnb7yZjv-2RjRCK8L1mqzxDnP0_lJBDvAPu7QzF7SVmb_gBmpo2n7w97B9mPjHpDOdDaPb-CDhngKZMOO4Xc79lrhTImsuVicf2mZOquVkhHq1JBR-KAcLf-9F","notification":{"body":"gdshgh","title":"jkhds","icon":"myicon","sound":"mysound","click_action":"OPEN_ACTIVITY"},"data":{"image":"http://www.propertynewsindia.in/wp-content/uploads/2013/11/Buy-A-New-Home.jpg"}}

which is a valid json output please help Thanks in Advance...

MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
NotificationUtils notificationUtils;
String imageUrl;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO: Handle FCM messages here.
    // If the application is in the foreground handle both data and notification messages here.
    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated.
    Log.e(TAG, "From: " + remoteMessage.getFrom());

    if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
        handleNotification(remoteMessage.getNotification().getBody());
    }

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

        try {
            JSONObject json = new JSONObject(remoteMessage.getData().toString());
            handleDataMessage(json);
        }catch (JSONException je){
            Log.e(TAG,"JSONException: "+je.getMessage());
        }
        catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
        NotificationCompat.Builder builder = new  NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("test")
                .setContentText(remoteMessage.getData().get("message"));
        NotificationManager manager = (NotificationManager)     getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
}
private void handleNotification(String message) {
    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
        // app is in foreground, broadcast the push message
        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

        // play notification sound
        notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.playNotificationSound();
        notificationUtils.getBitmapFromURL(imageUrl);
    }else{
        // If the app is in background, firebase itself handles the notification
    }
}

private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "push json: " + json.toString());

    try {
        JSONObject data = json.getJSONObject("data");

        String title = data.getString("title");
        String message = data.getString("message");
        boolean isBackground = data.getBoolean("is_background");
        String imageUrl = data.getString("image");
        String timestamp = data.getString("timestamp");
        JSONObject payload = data.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "message: " + message);
        Log.e(TAG, "isBackground: " + isBackground);
        Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);


        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the` push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        } else {
            // app is in background, show the notification in notification tray
            Intent resultIntent = new Intent(getApplicationContext(), Home.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

/**
 * Showing notification with text only
 */
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}

/**
 * Showing notification with text and image
 */
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}

}

NotificationUtills

public class NotificationUtils {
private static String TAG = NotificationUtils.class.getSimpleName();

private Context mContext;

public NotificationUtils(Context mContext) {
    this.mContext = mContext;
}

public void showNotificationMessage(String title, String message, String timeStamp, Intent intent) {
    showNotificationMessage(title, message, timeStamp, intent, null);
}

public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
    // Check for empty push message
    if (TextUtils.isEmpty(message))
        return;


    // notification icon
    final int icon = R.mipmap.ic_launcher;

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    final PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    mContext,
                    0,
                    intent,
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            mContext);

    final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
            + "://" + mContext.getPackageName() + "/raw/notification");

    if (!TextUtils.isEmpty(imageUrl)) {

        if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {

            Bitmap bitmap = getBitmapFromURL(imageUrl);

            if (bitmap != null) {
                showBigNotification(bitmap, mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
            } else {
                showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
            }
        }
    } else {
        showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
        playNotificationSound();
    }
}


private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    inboxStyle.addLine(message);

    Notification notification;
    notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(inboxStyle)
            .setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
            .setContentText(message)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Config.NOTIFICATION_ID, notification);
}

private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
    NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
    bigPictureStyle.setBigContentTitle(title);
    bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
    bigPictureStyle.bigPicture(bitmap);
    Notification notification;
    notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(bigPictureStyle)
            .setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
            .setContentText(message)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Config.NOTIFICATION_ID_BIG_IMAGE, notification);
}

/**
 * Downloading push notification image before displaying it in
 * the notification tray
 */
public Bitmap getBitmapFromURL(String strURL) {
    try {
        Log.i("URL-IMAGE",strURL);
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

// Playing notification sound
public void playNotificationSound() {
    try {
        Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/notification");
        Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Method checks if the app is in background or not
 */
public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}

// Clears notification tray messages
public static void clearNotifications(Context context) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

public static long getTimeMilliSec(String timeStamp) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date date = format.parse(timeStamp);
        return date.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return 0;
}

}

this is the new error i'm receving after the changes.....

KENdi
  • 7,576
  • 2
  • 16
  • 31
Snehal Gongle
  • 337
  • 3
  • 16
  • what does that means??? i didn't understand because i'm giving audio sound to the notification and that sound is been working properly – Snehal Gongle Jul 31 '17 at 11:29
  • are you passing just url OR whole payload as url to getBitmapFromUrl method? – Usman Rana Jul 31 '17 at 11:30
  • I'm passing only url and not all the values – Snehal Gongle Jul 31 '17 at 11:32
  • print that in this method, what you are receiving. – Usman Rana Jul 31 '17 at 11:33
  • Please tell me then what parameters should i pass do i have to pass all the parameters????? to get the right output???? Anyhow Thanks for your relay... – Snehal Gongle Jul 31 '17 at 11:33
  • @UsmanRana Ok let me see that – Snehal Gongle Jul 31 '17 at 11:34
  • look JSONObject data = json.getJSONObject("data"); String title = data.getString("title"); String message = data.getString("message"); boolean isBackground = data.getBoolean("is_background"); String imageUrl = data.getString("image"); String timestamp = data.getString("timestamp"); JSONObject payload = data.getJSONObject("payload"); these are the parameters that i needed – Snehal Gongle Jul 31 '17 at 11:35
  • @SnehalGongle please check this link [firebase-push-notification-android-with-image](http://androidbash.com/firebase-push-notification-android/) – AskNilesh Jul 31 '17 at 11:36
  • the issue in parsing of data. In getBitmapFromUrl method you print Logs that waht url are you using to download bitmap – Usman Rana Jul 31 '17 at 11:36
  • which i'm not sure about is the "is_background" – Snehal Gongle Jul 31 '17 at 11:36
  • and share the code of onMessageReceived function. The issue is in handling and parsing of data. – Usman Rana Jul 31 '17 at 11:39
  • if (remoteMessage.getData().size() > 0) { try { JSONObject json = new JSONObject(remoteMessage.getData().toString()); handleDataMessage(json); }catch (JSONException je){ Log.e(TAG,"JSONException: "+je.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } – Snehal Gongle Jul 31 '17 at 11:47
  • @usmanRana where remoteMessage is the output and handleDataMessage handles the json that is coming from server – Snehal Gongle Jul 31 '17 at 11:48
  • Edit your question and paste full code of Notification utils and MyFirebaseService. In comments code can't be read properly – Usman Rana Jul 31 '17 at 11:53
  • @UsmanRana I have edited my question and pasted the complete files please check the changes Thanks for all the help..... – Snehal Gongle Jul 31 '17 at 12:02
  • the jos that you are passing to handleDataMessage has only 1 value . "image" . use String imageUrl = json.getString("image"); , all other are not available in your payload so these are null – Usman Rana Jul 31 '17 at 12:06
  • @UsmanRana what is payload what should it be???? – Snehal Gongle Jul 31 '17 at 12:21
  • You are sending only "image" value in object "data":{"image":"http://www.propertynewsindia.in/wp-content/uploads/2013/11/Buy-A-New-Home.jpg"} . but in app you are getting more from it , which is causing issue – Usman Rana Jul 31 '17 at 12:36

1 Answers1

0

Currently you are sending only 1 vale "image" in notification data but reading other values as well which are missing in it,send json as following with all values that you want to read in app:

{
   {
   "to":"dJ4ege8LbI8:APA91bGqGQyIEBn2TsSnb7yZjv-2RjRCK8L1mqzxDnP0_lJBDvAPu7QzF7SVmb_gBmpo2n7w97B9mPjHpDOdDaPb-CDhngKZMOO4Xc79lrhTImsuVicf2mZOquVkhHq1JBR-KAcLf-9F",
   "notification":{  
      "body":"gdshgh",
      "title":"jkhds",
      "icon":"myicon",
      "sound":"mysound",
      "click_action":"OPEN_ACTIVITY"
   },
   "data":{  
      "data":{  
         "image":"http://www.propertynewsindia.in/wp-content/uploads/2013/11/Buy-A-New-Home.jpg"
      },
      "title":"My title",
      "message":"My message",
      "is_background":true,
      "timestamp:"2017-07-31 05:42:12",
      "payload":{  
         "name":"Test"
      }
   }
}

And parse the code data as following:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
NotificationUtils notificationUtils;
String imageUrl;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO: Handle FCM messages here.
    // If the application is in the foreground handle both data and notification messages here.
    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated.
    Log.e(TAG, "From: " + remoteMessage.getFrom());

    if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null && remoteMessage.getData().size()==0) {
        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
        handleNotification(remoteMessage.getNotification().getBody());
    }

    // Check if message contains a data payload.
    else if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

        try {
            JSONObject json = new JSONObject(remoteMessage.getData().getString("data"));
            handleDataMessage(json);
        }catch (JSONException je){
            Log.e(TAG,"JSONException: "+je.getMessage());
        }
        catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
        NotificationCompat.Builder builder = new  NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("test")
                .setContentText(remoteMessage.getData().get("message"));
        NotificationManager manager = (NotificationManager)     getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
}
private void handleNotification(String message) {
    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
        // app is in foreground, broadcast the push message
        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

        // play notification sound
        notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.playNotificationSound();
    }else{
        // If the app is in background, firebase itself handles the notification
    }
}

private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "push json: " + json.toString());

    try {

        String title = json.getString("title");
        String message = json.getString("message");
        boolean isBackground = json.getBoolean("is_background");
        String imageUrl = json.getString("image");
        String timestamp = json.getString("timestamp");
        JSONObject payload = json.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "message: " + message);
        Log.e(TAG, "isBackground: " + isBackground);
        Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);


        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the` push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        } else {
            // app is in background, show the notification in notification tray
            Intent resultIntent = new Intent(getApplicationContext(), Home.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

/**
 * Showing notification with text only
 */
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}

/**
 * Showing notification with text and image
 */
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}
Ashiqur Rahman
  • 425
  • 7
  • 21
Usman Rana
  • 2,067
  • 1
  • 21
  • 32
  • {"to":"dJ4ege8LbI8:APA91bGqGQyIEBn2TsSnb7yZjv-2RjRCK8L1mqzxDnP0_lJBDvAPu7QzF7SVmb_gBmpo2n7w97B9mPjHpDOdDaPb-CDhngKZMOO4Xc79lrhTImsuVicf2mZOquVkhHq1JBR-KAcLf-9F","notification":{"body":"jhdjsj","title":"jhgfdj","icon":"myicon","click_action":"OPEN_ACTIVITY"},"data":{"image":"http://www.propertynewsindia.in/wp-content/uploads/2013/11/Buy-A-New-Home.jpg","title":"my title","message":"my message","is_background":true,"timestamp":"2017-07-31 05:42:12","payload":{"title":"jhgfdj"}}} – Snehal Gongle Jul 31 '17 at 13:08
  • i got this json output and my appliction got terminated with java.lang.NullPointerException: println needs a message at public Bitmap getBitmapFromURL(String strURL) { try { Log.i("URL-IMAGE",strURL); – Snehal Gongle Jul 31 '17 at 13:11
  • i've changed the code for more ease to you. Use the updated code now – Usman Rana Jul 31 '17 at 13:22
  • i have changed the code accordingly and i got a diffrent error i have edited my question please check the newly added image Thanks for the help.... – Snehal Gongle Jul 31 '17 at 13:24
  • paste your "Data Payload" string here – Usman Rana Jul 31 '17 at 13:30
  • Data Payload: {payload={"name":"snehal"}, timestamp=2017-07-31 05:42:12, image=http://www.propertynewsindia.in/wp-content/uploads/2013/11/Buy-A-New-Home.jpg, title=my title, message=my message, is_background=true} – Snehal Gongle Jul 31 '17 at 13:30
  • JSONException: Unterminated object at character 50 of {payload={"name":"snehal"}, timestamp=2017-07-31 05:42:12, image=http://www.propertynewsindia.in/wp-content/uploads/2013/11/Buy-A-New-Home.jpg, title=my title, message=my message, is_background=true} – Snehal Gongle Jul 31 '17 at 13:43