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.ohmage.request.mobility.MobilityUploadRequest.java

/**
 * Creates a Mobility upload request.//from  w  w  w.jav a 2 s  .  c o m
 * 
 * @param httpRequest A HttpServletRequest that contains the parameters for
 *                  this request.
 * 
 * @throws InvalidRequestException Thrown if the parameters cannot be 
 *                            parsed.
 * 
 * @throws IOException There was an error reading from the request.
 */
public MobilityUploadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException {
    super(httpRequest, null);

    LOGGER.info("Creating a Mobility upload request.");

    validIds = new LinkedList<String>();
    invalidPointsMap = new HashMap<Integer, String>();
    invalidPointsJson = new LinkedList<JSONObject>();

    StreamUploadRequest tStreamUploadRequest = null;

    if (!isFailed()) {
        try {
            String[] dataArray = getParameterValues(InputKeys.DATA);
            if (dataArray.length == 0) {
                throw new ValidationException(ErrorCode.MOBILITY_INVALID_DATA,
                        "The upload data is missing: " + ErrorCode.MOBILITY_INVALID_DATA);
            } else if (dataArray.length > 1) {
                throw new ValidationException(ErrorCode.MOBILITY_INVALID_DATA,
                        "Multiple data parameters were given: " + ErrorCode.MOBILITY_INVALID_DATA);
            } else {
                JSONArray jsonDataArray;
                try {
                    jsonDataArray = new JSONArray(dataArray[0]);
                } catch (JSONException e) {
                    throw new ValidationException(ErrorCode.MOBILITY_INVALID_DATA,
                            "The data is not well formed.", e);
                }

                JSONArray resultDataArray = new JSONArray();
                for (int i = 0; i < jsonDataArray.length(); i++) {
                    JSONObject pointJson;
                    try {
                        pointJson = jsonDataArray.getJSONObject(i);
                    } catch (JSONException e) {
                        throw new ValidationException(ErrorCode.MOBILITY_INVALID_DATA,
                                "A Mobility data point was not a JSON object.", e);
                    }

                    MobilityPoint point;
                    try {
                        point = new MobilityPoint(pointJson, MobilityPoint.PrivacyState.PRIVATE);
                    } catch (DomainException e) {
                        invalidPointsMap.put(i, e.getMessage());
                        invalidPointsJson.add(pointJson);
                        continue;
                    }

                    validIds.add(point.getId().toString());

                    try {
                        JSONObject jsonPoint = new JSONObject();
                        if (MobilityPoint.Mode.ERROR.equals(point.getMode())) {
                            jsonPoint.put("stream_id", "error");

                            // Create the error object.
                            JSONObject errorObject = new JSONObject();
                            errorObject.put("mode", MobilityPoint.Mode.ERROR.toString().toLowerCase());

                            jsonPoint.put("data", errorObject);
                            jsonPoint.put("stream_version", 2012061300);
                        } else if (MobilityPoint.SubType.MODE_ONLY.equals(point.getSubType())) {
                            jsonPoint.put("stream_id", "mode_only");

                            // Create the mode object.
                            JSONObject modeObject = new JSONObject();
                            modeObject.put("mode", point.getMode().toString());

                            jsonPoint.put("data", modeObject);
                            jsonPoint.put("stream_version", 2012050700);
                        } else {
                            jsonPoint.put("stream_id", "extended");

                            // Add the sensor data and rename it to "data".
                            Collection<ColumnKey> columns = new LinkedList<ColumnKey>();
                            columns.add(MobilityColumnKey.SENSOR_DATA);
                            JSONObject mobilityJson;
                            try {
                                mobilityJson = point.toJson(false, columns);
                            } catch (DomainException e) {
                                throw new ValidationException(
                                        "The point could not be converted back to a JSON object.", e);
                            }
                            jsonPoint.put("data", mobilityJson.getJSONObject("sensor_data"));
                            jsonPoint.put("stream_version", 2012050700);
                        }

                        JSONObject metadata = new JSONObject();
                        metadata.put("id", point.getId().toString());
                        metadata.put("time", point.getTime());
                        metadata.put("timezone", point.getTimezone().getID());

                        Location location = point.getLocation();
                        if (location != null) {
                            try {
                                metadata.put("location", location.toJson(false, LocationColumnKey.ALL_COLUMNS));
                            } catch (DomainException e) {
                                throw new ValidationException(
                                        "The location could not be converted back to a JSON object.", e);
                            }
                        }
                        jsonPoint.put("metadata", metadata);

                        resultDataArray.put(jsonPoint);
                    } catch (JSONException e) {
                        throw new ValidationException("The stream information could not be built.", e);
                    }
                }

                tStreamUploadRequest = new StreamUploadRequest(httpRequest, getParameterMap(), OBSERVER_ID,
                        OBSERVER_VERSION, resultDataArray.toString(), false);
            }
        } catch (ValidationException e) {
            e.failRequest(this);
            e.logException(LOGGER);
        }
    }

    streamUploadRequest = tStreamUploadRequest;
}

From source file:com.soundcloud.playerapi.Token.java

/**
 * Construct a new token from a JSON response
 * @param json the json response//from w  w  w.  ja v a  2 s . co m
 * @throws IOException JSON format error
 */
public Token(JSONObject json) throws IOException {
    try {
        for (Iterator it = json.keys(); it.hasNext();) {
            final String key = it.next().toString();
            if (ACCESS_TOKEN.equals(key)) {
                access = json.getString(key);
            } else if (REFRESH_TOKEN.equals(key)) {
                // refresh token won't be set if we don't expire
                refresh = json.getString(key);
            } else if (EXPIRES_IN.equals(key)) {
                expiresIn = System.currentTimeMillis() + json.getLong(key) * 1000;
            } else if (SCOPE.equals(key)) {
                scope = json.getString(key);
            } else {
                // custom parameter
                customParameters.put(key, json.get(key).toString());
            }
        }
    } catch (JSONException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:app.com.example.android.sunshine.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.
 * <p/>//ww w  .  ja v a2 s. c  om
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
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();

        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);
        }
        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            // Student: call bulkInsert to add the weatherEntries to the database here
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }
        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + "Inserted");

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

From source file:com.example.android.myargmenuplanner.data.FetchJsonDataTask.java

private void getDataFoodFromJson(String JsonStr) throws JSONException {

    final String JSON_LIST = "foods";
    final String JSON_TITLE = "title";
    final String JSON_IMAGE_ID = "image_id";
    final String JSON_DESCRIPTION = "description";
    final String JSON_TIME = "time";
    final String JSON_ID = "id";

    try {//from w  w w .  j ava2s.co m
        JSONObject dataJson = new JSONObject(JsonStr);
        JSONArray moviesArray = dataJson.getJSONArray(JSON_LIST);

        Vector<ContentValues> cVVector = new Vector<ContentValues>(moviesArray.length());

        for (int i = 0; i < moviesArray.length(); i++) {

            JSONObject movie = moviesArray.getJSONObject(i);
            String title = movie.getString(JSON_TITLE);
            String image_id = movie.getString(JSON_IMAGE_ID);
            String description = movie.getString(JSON_DESCRIPTION);
            String time = movie.getString(JSON_TIME);
            String id = movie.getString(JSON_ID);

            ContentValues foodsValues = new ContentValues();

            foodsValues.put(FoodEntry.COLUMN_ID, id);
            foodsValues.put(FoodEntry.COLUMN_TITLE, title);
            foodsValues.put(FoodEntry.COLUMN_IMAGE_ID, image_id);
            foodsValues.put(FoodEntry.COLUMN_DESCRIPTION, description);
            foodsValues.put(FoodEntry.COLUMN_TIME, time);
            cVVector.add(foodsValues);

        }
        int inserted = 0;

        //            delete database
        int rowdeleted = mContext.getContentResolver().delete(FoodEntry.CONTENT_URI, null, null);

        //            // add to database
        Log.i(LOG_TAG, "Creando registros en base de datos. Tabla Food: ");
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);

            inserted = mContext.getContentResolver().bulkInsert(FoodEntry.CONTENT_URI, cvArray);
            Log.i(LOG_TAG, "Registros nuevos creados en tabla Food: " + inserted);
        }

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

}

From source file:com.example.android.myargmenuplanner.data.FetchJsonDataTask.java

private void getDataIngrFromJson(String JsonStr) throws JSONException {

    final String JSON_LIST = "ingredients";
    final String JSON_NAME = "name";
    final String JSON_QTY = "qty";
    final String JSON_UNIT = "unit";
    final String JSON_ID_FOOD = "id_food";

    try {/*from   www.  j  a  v a 2  s .c o m*/
        JSONObject dataJson = new JSONObject(JsonStr);
        JSONArray ingrArray = dataJson.getJSONArray(JSON_LIST);

        Vector<ContentValues> cVVector = new Vector<ContentValues>(ingrArray.length());

        for (int i = 0; i < ingrArray.length(); i++) {

            JSONObject ingr = ingrArray.getJSONObject(i);
            String id_food = ingr.getString(JSON_ID_FOOD);
            String name = ingr.getString(JSON_NAME);
            String qty = ingr.getString(JSON_QTY);
            String unit = ingr.getString(JSON_UNIT);

            ContentValues values = new ContentValues();

            values.put(IngrEntry.COLUMN_ID_FOOD, id_food);
            values.put(IngrEntry.COLUMN_NAME, name);
            values.put(IngrEntry.COLUMN_QTY, qty);
            values.put(IngrEntry.COLUMN_UNIT, unit);

            cVVector.add(values);

        }
        int inserted = 0;

        //            delete database
        int rowdeleted = mContext.getContentResolver().delete(IngrEntry.CONTENT_URI, null, null);

        //            // add to database
        Log.i(LOG_TAG, "Creando registros en base de datos. Tabla Ingredientes ");
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);

            inserted = mContext.getContentResolver().bulkInsert(IngrEntry.CONTENT_URI, cvArray);
            Log.i(LOG_TAG, "Registros nuevos creados en Tabla Ingredientes: " + inserted);
        }

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

}

From source file:com.redip.servlet.NonConformityActionList.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String echo = request.getParameter("sEcho");
    String sStart = request.getParameter("iDisplayStart");
    String sAmount = request.getParameter("iDisplayLength");
    String sCol = request.getParameter("iSortCol_0");
    String sdir = request.getParameter("sSortDir_0");
    String dir = "asc";
    String[] cols = { "Idqualitynonconformitiesaction", "action", "deadline", "follower", "status", "date",
            "percentage", "priority" };
    String[] follower = null;/*from ww  w . java2 s  .  co  m*/
    String[] date = null;
    String[] statusList = null;
    String[] deadline = null;
    String[] priority = null;

    if (request.getParameterValues("follower") != null) {
        follower = request.getParameterValues("follower");
    }
    if (request.getParameterValues("date") != null) {
        date = request.getParameterValues("date");
    }
    if (request.getParameterValues("status") != null) {
        statusList = request.getParameterValues("status");
    }
    if (request.getParameterValues("deadline") != null) {
        deadline = request.getParameterValues("deadline");
    }
    if (request.getParameterValues("priority") != null) {
        priority = request.getParameterValues("priority");
    }

    JSONObject result = new JSONObject();
    JSONArray array = new JSONArray();
    int amount = 10;
    int start = 0;
    int col = 0;

    String field1 = "";
    String field2 = "";
    String field3 = "";
    String field4 = "";
    String field5 = "";

    field1 = request.getParameter("sSearch_0");
    field2 = request.getParameter("sSearch_1");
    field3 = request.getParameter("sSearch_2");
    field4 = request.getParameter("sSearch_3");
    field5 = request.getParameter("sSearch_4");

    List<String> sArray = new ArrayList<String>();
    if (!field1.equals("")) {
        String sIdqualitynonconformitiesaction = " idqualitynonconformitiesaction like '%" + field1 + "%'";
        sArray.add(sIdqualitynonconformitiesaction);
    }
    if (!field2.equals("")) {
        String sAction = " action like '%" + field2 + "%'";
        sArray.add(sAction);
    }
    //        if (!problemDescription.equals("")) {
    //            String sProblemDescription = " problemDescription like '%" + problemDescription + "%'";
    //            sArray.add(sProblemDescription);
    //        }
    //        if (!status.equals("")) {
    //            String sStatus = " status like '%" + status + "%'";
    //            sArray.add(sStatus);
    //        }
    //        if (!severity.equals("")) {
    //            String sSeverity = " severity like '%" + severity + "%'";
    //            sArray.add(sSeverity);
    //        }

    if (follower != null) {
        String sFollower = " (";
        for (int a = 0; a < follower.length - 1; a++) {
            sFollower += " follower like '%" + follower[a] + "%' or";
        }
        sFollower += " follower like '%" + follower[follower.length - 1] + "%') ";
        sArray.add(sFollower);
    }
    if (date != null) {
        String sDate = " (";
        for (int a = 0; a < date.length - 1; a++) {
            sDate += " `date` like '%" + date[a] + "%' or";
        }
        sDate += " `date` like '%" + date[date.length - 1] + "%') ";
        sArray.add(sDate);
    }
    if (deadline != null) {
        String sDeadline = " (";
        for (int a = 0; a < deadline.length - 1; a++) {
            sDeadline += " deadline like '%" + deadline[a] + "%' or";
        }
        sDeadline += " deadline like '%" + deadline[deadline.length - 1] + "%') ";
        sArray.add(sDeadline);
    }
    //        if (fromDate != null) {
    //        String sFromDate = " fromDate > '" + fromDate + "'";
    //        sArray.add(sFromDate);
    //        }
    //        if (toDate != null) {
    //        String sFromDate = " fromDate > '" + toDate + "'";
    //        sArray.add(sFromDate);
    //        }
    if (priority != null) {
        String sPriority = " (";
        for (int a = 0; a < priority.length - 1; a++) {
            sPriority += " priority like '%" + priority[a] + "%' or";
        }
        sPriority += " priority like '%" + priority[priority.length - 1] + "%') ";
        sArray.add(sPriority);
    }
    if (statusList != null) {
        String sStatusList = " (";
        for (int a = 0; a < statusList.length - 1; a++) {
            sStatusList += " status like '%" + statusList[a] + "%' or";
        }
        sStatusList += " status like '%" + statusList[statusList.length - 1] + "%') ";
        sArray.add(sStatusList);
    }

    StringBuilder individualSearch = new StringBuilder();
    if (sArray.size() == 1) {
        individualSearch.append(sArray.get(0));
    } else if (sArray.size() > 1) {
        for (int i = 0; i < sArray.size() - 1; i++) {
            individualSearch.append(sArray.get(i));
            individualSearch.append(" and ");
        }
        individualSearch.append(sArray.get(sArray.size() - 1));
    }

    if (sStart != null) {
        start = Integer.parseInt(sStart);
        if (start < 0) {
            start = 0;
        }
    }
    if (sAmount != null) {
        amount = Integer.parseInt(sAmount);
        if (amount < 10 || amount > 100) {
            amount = 10;
        }
    }

    if (sCol != null) {
        col = Integer.parseInt(sCol);
        if (col < 0 || col > 5) {
            col = 0;
        }
    }
    if (sdir != null) {
        if (!sdir.equals("asc")) {
            dir = "desc";
        }
    }
    String colName = cols[col];

    String searchTerm = "";
    if (!request.getParameter("sSearch").equals("")) {
        searchTerm = request.getParameter("sSearch");
    }

    String inds = String.valueOf(individualSearch);

    JSONArray data = new JSONArray(); //data that will be shown in the table

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    IQualityNonconformitiesActionService qualityNonconformitiesActionService = appContext
            .getBean(IQualityNonconformitiesActionService.class);

    List<QualityNonconformitiesAction> nonconformitiesActionlist = qualityNonconformitiesActionService
            .getAllNonconformitiesAction(start, amount, colName, dir, searchTerm, inds);

    try {
        JSONObject jsonResponse = new JSONObject();

        for (QualityNonconformitiesAction listofnonconformitiesAction : nonconformitiesActionlist) {
            JSONArray row = new JSONArray();
            //"<a href=\'javascript:popup(\"qualitynonconformitydetails.jsp?ncid="+listofnonconformities.getIdqualitynonconformities()+"\")\'>"+listofnonconformities.getIdqualitynonconformities()+"</a>"
            row.put(listofnonconformitiesAction.getIdQualityNonconformitiesActions())
                    .put(listofnonconformitiesAction.getAction()).put(listofnonconformitiesAction.getFollower())
                    //                        .put(listofnonconformities.getRootCauseCategory())
                    //                        .put(listofnonconformities.getRootCauseDescription())
                    //                        .put(listofnonconformities.getResponsabilities())
                    .put(listofnonconformitiesAction.getStatus())
                    //                        .put(listofnonconformities.getComments())
                    .put(listofnonconformitiesAction.getDeadline())
                    .put("<a href=\"qualitynonconformitydetails.jsp?ncid="
                            + listofnonconformitiesAction.getIdQualityNonconformities() + "\">edit</a>");
            data.put(row);
        }
        jsonResponse.put("aaData", data);
        jsonResponse.put("sEcho", echo);
        jsonResponse.put("iTotalRecords", nonconformitiesActionlist.size());
        jsonResponse.put("iDisplayLength", data.length());
        jsonResponse.put("iTotalDisplayRecords", nonconformitiesActionlist.size());

        response.setContentType("application/json");
        response.getWriter().print(jsonResponse.toString());
    } catch (JSONException e) {
        Logger.log(NonConformityActionList.class.getName(), Level.FATAL, "" + e);
        response.setContentType("text/html");
        response.getWriter().print(e.getMessage());
    }
}

From source file:udatraining.dyomin.com.udaproj1.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 va2s.  com*/
 */
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();

        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(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(WeatherContract.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:se.chalmers.watchme.net.IMDBHandler.java

/**
 * Helper function to create a new JSONObject from a string.
 * //from w  ww .j  a  v  a 2 s .  c  om
 * <p>
 * Note that this function checks if the input string is a JSON array, e.g.
 * checks for square brackets in the beginning and end. If the string is an
 * array with a single JSON object, the object is parsed.
 * </p>
 * 
 * @param s
 *            The input string
 * @return A JSONObject from the string. Returns null if an error occurred
 *         while parsing the string
 */
public static JSONObject parseStringToJSON(String s) {
    JSONObject json = null;

    try {
        if (s.charAt(0) == '[' && s.charAt(s.length() - 1) == ']') {
            JSONArray ar = new JSONArray(s);
            json = ar.getJSONObject(0);
        } else {
            json = new JSONObject(s);
        }

    } catch (JSONException e) {
        System.err.println("Error while parsing JSONObject");
        System.err.println(e.getMessage());
        e.printStackTrace();
    }

    return json;
}

From source file:com.colossaldb.dnd.prefs.AppPreferences.java

private static JSONArray getJSONArray(SharedPreferences preferences, String listKey) {
    JSONArray events;/*from w w w  .j  a v  a  2s .  co m*/
    String eventStr = preferences.getString(listKey, null);
    if (eventStr == null) {
        events = new JSONArray();
    } else {
        try {
            events = new JSONArray(eventStr);
        } catch (JSONException ignored) {
            // Cannot do much...
            Log.e("AppPreferences", "Error: " + ignored.getMessage(), ignored);
            events = new JSONArray();
        }
    }
    return events;
}

From source file:com.example.guan.webrtc_android_7.common.WebSocketClient.java

public void register(final String roomID, final String clientID) {
    checkIfCalledOnValidThread();//from   w  w  w .j  a va2s  .  com
    this.roomID = roomID;
    this.clientID = clientID;
    if (state != WebSocketConnectionState.CONNECTED) {
        Log.w(TAG, "WebSocket register() in state " + state);
        return;
    }
    Log.d(TAG, "Registering WebSocket for room " + roomID + ". ClientID: " + clientID);
    JSONObject json = new JSONObject();
    try {
        json.put("cmd", "register");
        json.put("roomid", roomID);
        json.put("clientid", clientID);
        Log.d(TAG, "C->WSS: " + json.toString());
        ws.sendTextMessage(json.toString());
        state = WebSocketConnectionState.REGISTERED;
        // Send any previously accumulated messages.
        for (String sendMessage : wsSendQueue) {
            send(sendMessage);
        }
        wsSendQueue.clear();
        Log.e(TAG, "Success to Register WebSocket!");
    } catch (JSONException e) {
        reportError(roomID, "WebSocket register JSON error: " + e.getMessage());
    }
}