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:com.mio.jrdv.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.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from w  ww.  j av  a 2  s. co m*/
 */
private String[] 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);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////// ////////////////////////////////////////////////////////////////////////////////////////////
        //////NO SE USA SE PASA AL FORECAST ADAPTER
        // The lines in getWeatherDataFromJson where we requery the database after the insert.
        //vamoa acambiarlo por el nuevo FroreCastAdapter!!:
        ////////////////////////////////////////////////////////////////////////////////////////////

        //            // 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);
        //                mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        //
        //
        //            }
        //
        //            // Sort order:  Ascending, by date.
        //            String sortOrder = WeatherEntry.COLUMN_DATE + " ASC";
        //            Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(
        //                    locationSetting, System.currentTimeMillis());
        //
        //            // Students: Uncomment the next lines to display what what you stored in the bulkInsert
        //            //esto no hace nada !!lo que hace es que inserte 0!!!! si no lo hacemos por medio un bulkinsert!!
        //
        //            Cursor cur = mContext.getContentResolver().query(weatherForLocationUri,
        //                    null, null, null, sortOrder);
        //
        //            cVVector = new Vector<ContentValues>(cur.getCount());
        //            if ( cur.moveToFirst() ) {
        //                do {
        //                    ContentValues cv = new ContentValues();
        //                    DatabaseUtils.cursorRowToContentValues(cur, cv);
        //                    cVVector.add(cv);
        //                } while (cur.moveToNext());
        //            }
        //
        //            Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");
        //
        //            String[] resultStrs = convertContentValuesToUXFormat(cVVector);
        //            return resultStrs;

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            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();
    }
    return null;
}

From source file:com.prey.json.actions.Setting.java

public void update(Context ctx, List<ActionResult> lista, JSONObject parameters) {

    try {/* w  ww  .  j av  a  2 s  . c o m*/
        String key = parameters.getString("key");
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx);
        SharedPreferences.Editor editor = settings.edit();

        String value = parameters.getString("value");
        if (StringUtil.isTextBoolean(value)) {
            editor.putBoolean(key, Boolean.parseBoolean(value));
        } else {
            if (StringUtil.isTextInteger(value)) {
                editor.putInt(key, Integer.parseInt(value));
            } else {
                editor.putString(key, value);
            }
        }
        editor.commit();
    } catch (JSONException e) {
        PreyLogger.e("Error, causa:" + e.getMessage(), e);
    }
}

From source file:com.prey.json.actions.Setting.java

public void read(Context ctx, List<ActionResult> lista, JSONObject parameters) {

    HttpDataService data = new HttpDataService(Setting.DATA_ID);

    try {//from   ww w  .  j  a v  a 2 s.  com
        String key = parameters.getString("key");
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx);
        HashMap<String, String> parametersMap = new HashMap<String, String>();

        if (!"".equals(key)) {
            String value = settings.getString(key, "");
            if (!"".equals(value)) {
                parametersMap.put(key, value);
            }
        }
        data.addDataListAll(parametersMap);
        ActionResult result = new ActionResult();
        result.setDataToSend(data);

        lista.add(result);

        PreyLogger.d("Ejecuting Auto_update Action. DONE!");

    } catch (JSONException e) {
        PreyLogger.e("Error, causa:" + e.getMessage(), e);
    }
}

From source file:com.google.android.apps.gutenberg.provider.SyncAdapter.java

private static boolean didServerReturnNull(ExecutionException e) {
    if (e.getCause() instanceof ParseError) {
        ParseError cause = (ParseError) e.getCause();
        if (cause.getCause() instanceof JSONException) {
            JSONException causeCause = (JSONException) cause.getCause();
            if (causeCause.getMessage().contains("Value null of")) {
                return true;
            }//from  w ww  .j ava2s . c o m
        }
    }
    return false;
}

From source file:org.b3log.rhythm.repository.impl.TagRepositoryImpl.java

@Override
public List<JSONObject> getByArticleId(final String articleId) throws RepositoryException {
    final List<JSONObject> ret = new ArrayList<JSONObject>();

    try {//from  w ww  .  j a v  a2s . c o m
        final List<JSONObject> tagArticleRelations = tagArticleRepository.getByArticleId(articleId);
        for (final JSONObject tagArticleRelation : tagArticleRelations) {
            final String tagId = tagArticleRelation.getString(Tag.TAG + "_" + Keys.OBJECT_ID);
            final JSONObject tag = get(tagId);

            ret.add(tag);
        }
    } catch (final JSONException e) {
        LOGGER.error(e.getMessage());
        throw new RepositoryException(e);
    }

    return ret;
}

From source file:org.jabsorb.ng.serializer.impl.MapSerializer.java

@Override
public Object marshall(final SerializerState state, final Object p, final Object o) throws MarshallException {

    final Map<?, ?> map = (Map<?, ?>) o;
    final JSONObject obj = new JSONObject();
    final JSONObject mapdata = new JSONObject();

    if (ser.getMarshallClassHints()) {
        try {/*from www . ja  v a2  s  .co m*/
            obj.put("javaClass", o.getClass().getName());
        } catch (final JSONException e) {
            throw new MarshallException("javaClass not found!", e);
        }
    }

    try {
        obj.put("map", mapdata);
        state.push(o, mapdata, "map");
    } catch (final JSONException e) {
        throw new MarshallException("Could not add map to object: " + e.getMessage(), e);
    }

    Object key = null;
    try {
        for (final Entry<?, ?> entry : map.entrySet()) {
            key = entry.getKey();
            final String keyString = key.toString(); // only support String
                                                     // keys

            final Object json = ser.marshall(state, mapdata, entry.getValue(), keyString);

            // omit the object entirely if it's a circular reference or
            // duplicate
            // it will be regenerated in the fixups phase
            if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) {
                mapdata.put(keyString, json);
            }
        }
    } catch (final MarshallException e) {
        throw new MarshallException("map key " + key + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new MarshallException("map key " + key + " " + e.getMessage(), e);
    } finally {
        state.pop();
    }
    return obj;
}

From source file:org.jabsorb.ng.serializer.impl.MapSerializer.java

@Override
public ObjectMatch tryUnmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    final JSONObject jso = (JSONObject) o;
    String java_class;

    // Hint presence
    try {//from www  . ja  v  a 2  s  .  c o m
        java_class = jso.getString("javaClass");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read javaClass", e);
    }
    if (java_class == null) {
        throw new UnmarshallException("no type hint");
    }

    // Class compatibility check
    if (!classNameCheck(java_class)) {
        // FIXME: previous version also handled Properties
        throw new UnmarshallException("not a Map");
    }

    // JSON Format check
    JSONObject jsonmap;
    try {
        jsonmap = jso.getJSONObject("map");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read map: " + e.getMessage(), e);
    }
    if (jsonmap == null) {
        throw new UnmarshallException("map missing");
    }

    // Content check
    final ObjectMatch m = new ObjectMatch(-1);
    state.setSerialized(o, m);

    final Iterator<?> i = jsonmap.keys();
    String key = null;
    try {
        while (i.hasNext()) {
            key = (String) i.next();
            m.setMismatch(ser.tryUnmarshall(state, null, jsonmap.get(key)).max(m).getMismatch());
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    }
    return m;
}

From source file:org.jabsorb.ng.serializer.impl.MapSerializer.java

@Override
public Object unmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    final JSONObject jso = (JSONObject) o;
    String java_class;

    // Hint check
    try {/*from w w w. j av a 2  s. co  m*/
        java_class = jso.getString("javaClass");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read javaClass", e);
    }

    if (java_class == null) {
        throw new UnmarshallException("no type hint");
    }

    // Create the map
    final Map<Object, Object> abmap;
    if (java_class.equals("java.util.Map") || java_class.equals("java.util.AbstractMap")
            || java_class.equals("java.util.HashMap")) {
        abmap = new HashMap<Object, Object>();
    } else if (java_class.equals("java.util.TreeMap")) {
        abmap = new TreeMap<Object, Object>();
    } else if (java_class.equals("java.util.LinkedHashMap")) {
        abmap = new LinkedHashMap<Object, Object>();
    } else if (java_class.equals("java.util.Properties")) {
        abmap = new Properties();
    } else {
        throw new UnmarshallException("not a Map");
    }

    // Parse the JSON map
    JSONObject jsonmap;
    try {
        jsonmap = jso.getJSONObject("map");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read map: " + e.getMessage(), e);
    }
    if (jsonmap == null) {
        throw new UnmarshallException("map missing");
    }

    state.setSerialized(o, abmap);

    final Iterator<?> i = jsonmap.keys();
    String key = null;
    try {
        while (i.hasNext()) {
            key = (String) i.next();
            abmap.put(key, ser.unmarshall(state, null, jsonmap.get(key)));
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    }

    return abmap;
}

From source file:com.nebel_tv.content.services.VideoAssetsServiceTest.java

/**
 * Test of getVideoAssets request of service IvaWrapperWeb
 *
 * @param url Service URL//ww  w .  j  ava  2  s . c  om
 */
public void testServiceRequest(String url) {
    try {
        String response = IOUtils.toString(new URL(url));
        assertTrue(response != null && !response.isEmpty());

        JSONArray jsonVideoAssets = new JSONArray(response);
        assertFalse(jsonVideoAssets.length() == 0);

        for (int i = 0; i < jsonVideoAssets.length(); i++) {
            JSONObject jsonItem = jsonVideoAssets.getJSONObject(i);
            testJsonVideoAsset(jsonItem);
        }
    } catch (JSONException e) {
        fail("JSON parsing failed" + e.getMessage());
    } catch (IOException e) {
        fail("Web service request failed " + e.getMessage());
    }
}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

private void addGeofence(CallbackContext callbackContext, JSONObject config) {
    try {/* w w w  .j a v a  2  s.  c o  m*/
        String identifier = config.getString("identifier");
        final Bundle event = new Bundle();
        event.putString("name", BackgroundGeolocationService.ACTION_ADD_GEOFENCE);
        event.putBoolean("request", true);
        event.putFloat("radius", (float) config.getLong("radius"));
        event.putDouble("latitude", config.getDouble("latitude"));
        event.putDouble("longitude", config.getDouble("longitude"));
        event.putString("identifier", identifier);

        if (config.has("notifyOnEntry")) {
            event.putBoolean("notifyOnEntry", config.getBoolean("notifyOnEntry"));
        }
        if (config.has("notifyOnExit")) {
            event.putBoolean("notifyOnExit", config.getBoolean("notifyOnExit"));
        }
        if (config.has("notifyOnDwell")) {
            event.putBoolean("notifyOnDwell", config.getBoolean("notifyOnDwell"));
        }
        if (config.has("loiteringDelay")) {
            event.putInt("loiteringDelay", config.getInt("loiteringDelay"));
        }
        addGeofenceCallbacks.put(identifier, callbackContext);

        postEvent(event);

    } catch (JSONException e) {
        e.printStackTrace();
        callbackContext.error(e.getMessage());
    }
}