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.home883.ali.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  w w  .java2s . com
 */
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);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cVArray = cVVector.toArray(new ContentValues[cVVector.size()]);
            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

        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;

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

From source file:se.frostyelk.cordova.parse.plugin.ParsePlugin.java

private PluginResult initialize(final CallbackContext callbackContext, final JSONArray args) {
    try {//from   w  ww.  j a  va  2 s.com
        appId = args.getString(0);
        clientKey = args.getString(1);
        Parse.initialize(cordova.getActivity().getApplicationContext(), appId, clientKey);
        ParseInstallation.getCurrentInstallation().saveInBackground();
        ParseAnalytics.trackAppOpenedInBackground(cordova.getActivity().getIntent());
        callbackContext.success();
    } catch (JSONException e) {
        callbackContext.error("JSONException: " + e.getMessage());
    }

    return null;
}

From source file:fr.cph.stock.android.entity.EntityBuilder.java

public User getUser() {
    if (user == null) {
        try {/*from   ww  w.  j a  va  2 s . c om*/
            buildEquities();
        } catch (JSONException e) {
            Log.e(TAG, e.getMessage(), e);
            portfolio = null;
            user = null;
        }
    }
    return user;
}

From source file:fr.cph.stock.android.entity.EntityBuilder.java

public Portfolio getPortfolio() {
    if (portfolio == null) {
        try {//from   w  w  w  .  ja  v  a 2s.c o  m
            buildEquities();
        } catch (JSONException e) {
            Log.e(TAG, e.getMessage(), e);
            portfolio = null;
            user = null;
        }
    }
    return portfolio;
}

From source file:com.ota.updates.json.AddonJSONParser.java

/**
 * Parse the Addons array within the selected JSON string
 *//*from  ww  w  .  j a va 2  s  . com*/
public boolean parse() {
    try {
        JSONObject jObj = new JSONObject(mJSONString);

        JSONObject romObj = jObj.getJSONObject(NAME_ROM);

        JSONArray addonsArr = romObj.getJSONArray(NAME_ADDONS);

        AddonSQLiteHelper helper = new AddonSQLiteHelper(mContext);

        for (int i = 0; i < addonsArr.length(); i++) {
            JSONObject arrayObj = addonsArr.getJSONObject(i);

            JSONObject versionObj = arrayObj.getJSONObject(NAME_ADDON);

            AddonItem addonItem = new AddonItem();

            addonItem.setId(versionObj.getInt(NAME_ID));
            addonItem.setDownloads(versionObj.getInt(NAME_DOWNLOADS));
            addonItem.setName(versionObj.getString(NAME_NAME));
            addonItem.setSlug(versionObj.getString(NAME_SLUG));
            addonItem.setDescription(versionObj.getString(NAME_DESCRIPTION));
            addonItem.setCreatedAt(versionObj.getString(NAME_CREATED_AT));
            addonItem.setPublishedAt(versionObj.getString(NAME_PUBLISHED_AT));
            addonItem.setSize(versionObj.getInt(NAME_SIZE));
            addonItem.setMd5(versionObj.getString(NAME_MD5));
            addonItem.setDownloadLink(versionObj.getString(NAME_DOWNLOAD_LINK));
            addonItem.setCategory(versionObj.getString(NAME_CATEGORY));
            helper.addAddon(addonItem);
        }
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
        return false;
    }
    return true;
}

From source file:de.egore911.drilog.adapter.ShowDataAdapter.java

public void updateElements(JSONObject o, Set<String> watchList) {
    this.watchList = watchList;
    // Prepare the data
    this.listElements = new ArrayList<ListElement>();
    if (o != null) {
        try {/*from   w  w w.j av a  2  s  .  c  o  m*/
            // Read some static data from the JSON-Structure
            channel = o.getString("channel");
            date = DateUtil.getDate(o.getString("date"));
            maxDate = DateUtil.getDate(o.getString("maxdate"));

            Map<String, User> userMap = new HashMap<String, User>();
            // Now let's read the users
            JSONArray users = o.getJSONArray("users");
            for (int i = 0; i < users.length(); i++) {
                JSONObject user = users.getJSONObject(i);
                User u = User.create(user);
                userMap.put(user.getString("name"), u);
            }

            // Now read the log lines
            User lastUser = null;
            JSONArray data = o.getJSONArray("data");
            for (int i = 0; i < data.length(); i++) {
                // Now let's add the log lines from this user
                JSONObject comment = data.getJSONObject(i);
                Comment c = Comment.create(comment);
                User user = userMap.get(comment.getString("user"));
                c.user = user;
                if (lastUser != user) {
                    listElements.add(user);
                    lastUser = user;
                }
                listElements.add(c);
            }
        } catch (JSONException e) {
            Log.e(this.getClass().getSimpleName(), e.getMessage(), e);
        }
    }
    notifyDataSetChanged();
}

From source file:org.dasein.cloud.rackspace.CDNMethod.java

public JSONArray get() throws CloudException, InternalException {
    AuthenticationContext context = provider.getAuthenticationContext();

    String response = getString(context.getStorageToken(), context.getCdnUrl(), "?format=json");

    if (response == null) {
        return null;
    }/*from   w ww . j a  v a 2  s. c  o  m*/
    try {
        return new JSONArray(response);
    } catch (JSONException e) {
        throw new CloudException("Invalid JSON from server: " + e.getMessage());
    }
}

From source file:org.jabsorb.ng.serializer.impl.ListSerializer.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 w  ww. ja va 2s. 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)) {
        throw new UnmarshallException("not a List");
    }

    // JSON Format check
    JSONArray jsonlist;
    try {
        jsonlist = jso.getJSONArray("list");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read list: " + e.getMessage(), e);
    }
    if (jsonlist == null) {
        throw new UnmarshallException("list missing");
    }

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

    int idx = 0;
    try {
        for (idx = 0; idx < jsonlist.length(); idx++) {
            m.setMismatch(ser.tryUnmarshall(state, null, jsonlist.get(idx)).max(m).getMismatch());
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("element " + idx + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("element " + idx + " " + e.getMessage(), e);
    }
    return m;
}

From source file:org.jabsorb.ng.serializer.impl.ListSerializer.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 {//  ww  w  .j  av a2  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 list
    final AbstractList<Object> ablist;
    if (java_class.equals("java.util.List") || java_class.equals("java.util.AbstractList")
            || java_class.equals("java.util.ArrayList")) {
        ablist = new ArrayList<Object>();
    } else if (java_class.equals("java.util.LinkedList")) {
        ablist = new LinkedList<Object>();
    } else if (java_class.equals("java.util.Vector")) {
        ablist = new Vector<Object>();
    } else {
        throw new UnmarshallException("not a List");
    }

    // Parse the JSON list
    JSONArray jsonlist;
    try {
        jsonlist = jso.getJSONArray("list");

    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read list: " + e.getMessage(), e);
    }

    if (jsonlist == null) {
        throw new UnmarshallException("list missing");
    }

    state.setSerialized(o, ablist);

    int idx = 0;
    try {
        for (idx = 0; idx < jsonlist.length(); idx++) {
            ablist.add(ser.unmarshall(state, null, jsonlist.get(idx)));
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("element " + idx + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("element " + idx + " " + e.getMessage(), e);
    }
    return ablist;
}

From source file:face4j.response.PhotoResponseImpl.java

public PhotoResponseImpl(final String json) throws FaceClientException {
    super(json);/*from w  w  w .ja  v  a  2  s. c  o  m*/

    try {
        photos = toPhotoList(response.getJSONArray("photos"));
    }

    catch (JSONException jex) {
        logger.error("Error getting photos: " + jex.getMessage(), jex);
        throw new FaceClientException(jex);
    }
}