Example usage for org.json JSONException getMessage

List of usage examples for org.json JSONException getMessage

Introduction

In this page you can find the example usage for org.json JSONException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.lafs.hdfs.LAFS.java

private FileStatus getStatusFromJSON(JSONArray ja, Path path) throws IOException {
    FileStatus stat;/*from   w w w . ja  va 2  s .com*/

    String flag;
    try {
        flag = ja.getString(0);

        boolean isDir = flag.equals("dirnode");

        JSONObject data = ja.getJSONObject(1);

        long mtime = 0L;
        if (data.has("metadata"))
            mtime = (long) data.getJSONObject("metadata").getJSONObject("tahoe").getDouble("linkmotime");

        // each file consists of 1 block of a size the entire length of the file

        long size = 0L;

        if (!isDir) {
            try {
                size = (long) data.getInt("size");
            } catch (JSONException joe) {
                logger.warning("size was null");
            }
        }
        //else 
        //   size = data.getJSONObject("children").length();

        stat = new FileStatus(isDir ? 0 : size, isDir, 1, size, mtime, path);
    } catch (JSONException e) {
        logger.severe(ja.toString());
        throw new IOException(e.getMessage());
    }

    return stat;
}

From source file:org.lafs.hdfs.LAFS.java

@SuppressWarnings("unchecked")
@Override// w  w w.  ja v  a  2s.  co m
public FileStatus[] listStatus(Path path) throws IOException {
    FileStatus[] ret = null;

    JSONArray ja = getJSONForPath(path);

    try {
        String flag = ja.getString(0);
        boolean isDir = flag.equals("dirnode");

        if (isDir) { // process directory
            String pathString = path.toString();
            if (!pathString.endsWith("/"))
                pathString = pathString + "/";

            JSONObject data = ja.getJSONObject(1);

            // get the status of each child
            ArrayList<FileStatus> stats = new ArrayList<>();
            JSONObject children = data.getJSONObject("children");
            Iterator<String> items = children.keys();
            while (items.hasNext()) {
                String name = items.next();

                FileStatus stat = getStatusFromJSON(children.getJSONArray(name), new Path(pathString + name));
                stats.add(stat);
            }

            ret = new FileStatus[stats.size()];
            ret = stats.toArray(ret);
        } else { // process a file   
            FileStatus stat = getStatusFromJSON(ja, path);
            ret = new FileStatus[1];
            ret[0] = stat;
        }

    } catch (JSONException e) {
        throw new IOException(e.getMessage());
    }

    return ret;
}

From source file:com.phonegap.plugins.childbrowser.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//from   www .  ja va2  s.c  o  m
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
        showNavigationBar = options.optBoolean("showNavigationBar", true);
        showAddress = options.optBoolean("showAddress", true);
    }

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        public void run() {
            dialog = new Dialog((Context) cordova.getActivity());

            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    webview.stopLoading();
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams forwardParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, 1.0f);
            LinearLayout.LayoutParams closeParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams wvParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT);
            if (!showAddress) // larger buttons if address bar is not visible
            {
                backParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
                        1.0f);
                forwardParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT, 1.0f);
                closeParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
                        1.0f);
            }

            LinearLayout main = new LinearLayout((Context) cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            LinearLayout toolbar = new LinearLayout((Context) cordova.getActivity());
            toolbar.setOrientation(LinearLayout.HORIZONTAL);

            ImageButton back = new ImageButton((Context) cordova.getActivity());
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });
            back.setId(1);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setLayoutParams(backParams);

            ImageButton forward = new ImageButton((Context) cordova.getActivity());
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });
            forward.setId(2);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setLayoutParams(forwardParams);

            edittext = new EditText((Context) cordova.getActivity());
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });
            edittext.setId(3);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setLayoutParams(editParams);

            ImageButton close = new ImageButton(cordova.getActivity());
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });
            close.setId(4);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setLayoutParams(closeParams);

            webview = new WebView((Context) cordova.getActivity());
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setBuiltInZoomControls(true);
            WebViewClient client = new ChildBrowserClient(cordova, edittext);
            webview.setWebViewClient(client);
            webview.loadUrl(url);
            webview.setId(5);
            webview.setInitialScale(0);
            webview.setLayoutParams(wvParams);
            webview.requestFocus();
            webview.requestFocusFromTouch();
            webview.getSettings().setUseWideViewPort(true);
            webview.getSettings().setLoadWithOverviewMode(true);
            toolbar.addView(back);
            toolbar.addView(forward);
            toolbar.addView(edittext);
            toolbar.addView(close);

            if (getShowLocationBar()) {
                main.addView(toolbar);
            }
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);

            if (!showNavigationBar) {
                back.setVisibility(View.GONE);
                forward.setVisibility(View.GONE);
                close.setVisibility(View.GONE);
            }
            if (!showAddress) {
                edittext.setVisibility(View.GONE);
            }
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:org.csploit.android.gui.dialogs.ChangelogDialog.java

@SuppressLint("SetJavaScriptEnabled")
public ChangelogDialog(final Activity activity) {
    super(activity);

    this.setTitle("Changelog");

    TextView view = new TextView(activity);

    this.setView(view);

    if (mLoader == null)
        mLoader = ProgressDialog.show(activity, "", getContext().getString(R.string.loading_changelog));

    try {/*from ww  w  . j a  v  a2s .  c o  m*/
        view.setText(GitHubParser.getcSploitRepo().getReleaseBody(System.getAppVersionName()));
    } catch (JSONException e) {
        view.setText(Html.fromHtml(ERROR_HTML.replace("{DESCRIPTION}", e.getMessage())));
        System.errorLogging(e);
    } catch (IOException e) {
        view.setText(Html.fromHtml(ERROR_HTML.replace("{DESCRIPTION}", e.getMessage())));
        Logger.error(e.getMessage());
    }

    mLoader.dismiss();

    this.setCancelable(false);
    this.setButton(BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });
}

From source file:com.prashantpal.sunshine.app.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./* w w w .  j a  v a  2 s .c  o m*/
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();
        int inserted = 0;
        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted");

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:com.taobao.wuzhong.plugins.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/* w w  w  .ja  v a2  s  .co m*/
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        public void run() {
            dialog = new Dialog(ctx.getContext(), android.R.style.Theme_Translucent_NoTitleBar);

            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams forwardParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, 1.0f);
            LinearLayout.LayoutParams closeParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams wvParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT);

            LinearLayout main = new LinearLayout(ctx.getContext());
            main.setOrientation(LinearLayout.VERTICAL);

            LinearLayout toolbar = new LinearLayout(ctx.getContext());
            toolbar.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            toolbar.setOrientation(LinearLayout.HORIZONTAL);

            ImageButton back = new ImageButton(ctx.getContext());
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });
            back.setId(1);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setLayoutParams(backParams);

            ImageButton forward = new ImageButton(ctx.getContext());
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });
            forward.setId(2);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setLayoutParams(forwardParams);

            edittext = new EditText(ctx.getContext());
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });
            edittext.setId(3);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setLayoutParams(editParams);

            ImageButton close = new ImageButton(ctx.getContext());
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });
            close.setId(4);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setLayoutParams(closeParams);

            webview = new WebView(ctx.getContext());
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(5);
            webview.setInitialScale(0);
            webview.setLayoutParams(wvParams);
            webview.requestFocus();
            webview.requestFocusFromTouch();

            toolbar.addView(back);
            toolbar.addView(forward);
            toolbar.addView(edittext);
            toolbar.addView(close);

            if (getShowLocationBar()) {
                main.addView(toolbar);
            }
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = ctx.getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.ctx.runOnUiThread(runnable);
    return "";
}

From source file:com.facebook.android.FriendsList.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mHandler = new Handler();
    setContentView(R.layout.friends_list);

    Bundle extras = getIntent().getExtras();
    String apiResponse = extras.getString("API_RESPONSE");
    graph_or_fql = extras.getString("METHOD");
    try {//from w w  w .ja  v  a2  s . co  m
        if (graph_or_fql.equals("graph")) {
            jsonArray = new JSONObject(apiResponse).getJSONArray("data");
        } else {
            jsonArray = new JSONArray(apiResponse);
        }
    } catch (JSONException e) {
        showToast("Error: " + e.getMessage());
        return;
    }
    friendsList = (ListView) findViewById(R.id.friends_list);
    friendsList.setOnItemClickListener(this);
    friendsList.setAdapter(new FriendListAdapter(this));

    showToast(getString(R.string.can_post_on_wall));
}

From source file:com.facebook.android.FriendsList.java

@Override
@SuppressWarnings("deprecation")
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
    try {//w  ww  . j a  va 2s  .c  o  m
        final long friendId;
        if (graph_or_fql.equals("graph")) {
            friendId = jsonArray.getJSONObject(position).getLong("id");
        } else {
            friendId = jsonArray.getJSONObject(position).getLong("uid");
        }
        String name = jsonArray.getJSONObject(position).getString("name");

        new AlertDialog.Builder(this).setTitle(R.string.post_on_wall_title)
                .setMessage(String.format(getString(R.string.post_on_wall), name))
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Bundle params = new Bundle();
                        /*
                         * Source Tag: friend_wall_tag To write on a friend's wall, 
                         * provide friend's UID in the 'to' parameter.
                         * More info on feed dialog:
                         * https://developers.facebook.com/docs/reference/dialogs/feed/
                         */
                        params.putString("to", String.valueOf(friendId));
                        params.putString("caption", getString(R.string.app_name));
                        params.putString("description", getString(R.string.app_desc));
                        params.putString("picture", Utility.HACK_ICON_URL);
                        params.putString("name", getString(R.string.app_action));
                        Utility.mFacebook.dialog(FriendsList.this, "feed", params, new PostDialogListener());
                    }

                }).setNegativeButton(R.string.no, null).show();
    } catch (JSONException e) {
        showToast("Error: " + e.getMessage());
    }
}

From source file:com.procasy.dubarah_nocker.gcm.MyGcmPushReceiver.java

/**
 * Processing chat room push message//from   w  ww .  jav a  2  s  .c o  m
 * this message will be broadcasts to all the activities registered
 */
private void processChatRoomPush(String title, boolean isBackground, String data) {
    if (!isBackground) {

        try {
            JSONObject datObj = new JSONObject(data);

            String chatRoomId = datObj.getString("chat_room_id");

            JSONObject mObj = datObj.getJSONObject("message");
            Message message = new Message();
            message.setMessage(mObj.getString("message"));
            message.setId(mObj.getString("message_id"));
            message.setCreatedAt(mObj.getString("created_at"));

            JSONObject uObj = datObj.getJSONObject("user");

            // skip the message if the message belongs to same user as
            // the user would be having the same message when he was sending
            // but it might differs in your scenario

            /// TODO: 8/2/2016 remove to process chat
            /*       if (uObj.getString("user_id").equals(MyApplication.getInstance().getPrefManager().getUser().getId())) {
            Log.e(TAG, "Skipping the push message as it belongs to same user");
            return;
                   }*/

            User user = new User();
            user.setId(uObj.getString("user_id"));
            user.setEmail(uObj.getString("email"));
            user.setName(uObj.getString("name"));
            message.setUser(user);

            // verifying whether the app is in background or foreground
            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {

                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(GCMConfig.PUSH_NOTIFICATION);
                pushNotification.putExtra("type", GCMConfig.PUSH_TYPE_CHATROOM);
                pushNotification.putExtra("message", message);
                pushNotification.putExtra("chat_room_id", chatRoomId);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils();
                notificationUtils.playNotificationSound();
            } else {

                // app is in background. show the message in notification try
                Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
                resultIntent.putExtra("chat_room_id", chatRoomId);
                showNotificationMessage(getApplicationContext(), title,
                        user.getName() + " : " + message.getMessage(), message.getCreatedAt(), resultIntent);
            }

        } catch (JSONException e) {
            Log.e(TAG, "json parsing error: " + e.getMessage());
            Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }

    } else {
        // the push notification is silent, may be other operations needed
        // like inserting it in to SQLite
    }
}

From source file:com.procasy.dubarah_nocker.gcm.MyGcmPushReceiver.java

/**
 * Processing user specific push message
 * It will be displayed with / without image in push notification tray
 *//*www.  j  a v a 2s .c  o  m*/
private void processUserMessage(String title, boolean isBackground, String data) {
    if (!isBackground) {

        String chatRoomId;
        try {
            JSONObject datObj = new JSONObject(data);
            JSONObject mObj = datObj.getJSONObject("message");
            Message message = new Message();
            message.setMessage(mObj.getString("message"));
            message.setId(mObj.getString("message_id"));
            message.setCreatedAt(mObj.getString("created_at"));
            chatRoomId = mObj.getString("chat_room_id");
            JSONObject uObj = datObj.getJSONObject("user");
            User user = new User();
            user.setId(uObj.getString("user_id"));
            user.setEmail(uObj.getString("email"));
            user.setName(uObj.getString("name"));
            message.setUser(user);

            // verifying whether the app is in background or foreground
            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {

                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(GCMConfig.PUSH_NOTIFICATION);
                pushNotification.putExtra("type", GCMConfig.PUSH_TYPE_USER);
                pushNotification.putExtra("message", message);
                pushNotification.putExtra("chat_room_id", chatRoomId);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils();
                notificationUtils.playNotificationSound();
            } else {
                Intent resultIntent = new Intent(getApplicationContext(), ChatRoomActivity.class);
                resultIntent.putExtra("chat_room_id", chatRoomId);
                showNotificationMessage(getApplicationContext(), title, message.getMessage(),
                        message.getCreatedAt(), resultIntent);

            }
        } catch (JSONException e) {
            Log.e(TAG, "json parsing error: " + e.getMessage());
            Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }

    } else {
        // the push notification is silent, may be other operations needed
        // like inserting it in to SQLite
    }
}