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.steveleach.scoresheet.ui.ScoresheetActivity.java

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    Log.d(LOG_TAG, "ScoresheetActivity.onRestoreInstanceState");
    String jsonText = savedInstanceState.getString(STATE_KEY);
    if (jsonText != null) {
        try {// w w  w  .java 2  s  .c  o m
            jsonCodec.fromJson(model, jsonText);
            model.notifyListeners(ModelUpdate.ALL_CHANGED);
        } catch (JSONException e) {
            toast("Error parsing json: " + e.getMessage());
        }
    }
}

From source file:org.steveleach.scoresheet.ui.ScoresheetActivity.java

@Override
public void onSaveInstanceState(Bundle outState) {
    Log.d(LOG_TAG, "ScoresheetActivity.onSaveInstanceState");
    try {//  w w  w .  j a  v a 2  s .c  om
        String modelJson = jsonCodec.toJson(model);
        outState.putCharSequence(STATE_KEY, modelJson);
    } catch (JSONException e) {
        toast("Error creating json: " + e.getMessage());
    }
}

From source file:org.matrix.console.store.LoginStorage.java

/**
 * Return a list of HomeserverConnectionConfig.
 * @return a list of HomeserverConnectionConfig.
 *///from  ww w.java2  s. c o  m
public ArrayList<HomeserverConnectionConfig> getCredentialsList() {
    SharedPreferences prefs = mContext.getSharedPreferences(PREFS_LOGIN, Context.MODE_PRIVATE);

    String connectionConfigsString = prefs.getString(PREFS_KEY_CONNECTION_CONFIGS, null);

    Log.d(LOG_TAG, "Got connection json: " + connectionConfigsString);

    if (connectionConfigsString == null) {
        return new ArrayList<HomeserverConnectionConfig>();
    }

    try {

        JSONArray connectionConfigsStrings = new JSONArray(connectionConfigsString);

        ArrayList<HomeserverConnectionConfig> configList = new ArrayList<HomeserverConnectionConfig>(
                connectionConfigsStrings.length());

        for (int i = 0; i < connectionConfigsStrings.length(); i++) {
            configList.add(HomeserverConnectionConfig.fromJson(connectionConfigsStrings.getJSONObject(i)));
        }

        return configList;
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Failed to deserialize accounts " + e.getMessage(), e);
        throw new RuntimeException("Failed to deserialize accounts");
    }
}

From source file:com.hyphenated.pokerplayerclient.domain.PlayerStatus.java

public PlayerStatus(JSONObject json) {
    try {/*from   w  w w . jav  a  2s  .c  om*/
        status = PlayerStatusType.valueOf(json.getString("status"));
        if (json.has("card1")) {
            this.card1 = Card.getCardByIdentifier(json.getString("card1"));
            this.card2 = Card.getCardByIdentifier(json.getString("card2"));
        }
        if (json.has("chips")) {
            this.chips = json.getInt("chips");
        }
        if (json.has("amountBetRound")) {
            this.amountBetRound = json.getInt("amountBetRound");
        }
        if (json.has("amountToCall")) {
            this.amountToCall = json.getInt("amountToCall");
        }
        if (json.has("smallBlind")) {
            this.smallBlind = json.getInt("smallBlind");
        }
        if (json.has("bigBlind")) {
            this.bigBlind = json.getInt("bigBlind");
        }
    } catch (JSONException e) {
        Log.e("Poker", e.getMessage());
    }
}

From source file:com.orange.mmp.api.ws.jsonrpc.SimpleMapSerializer.java

@SuppressWarnings("unchecked")
@Override//from  w ww.  j a  va  2 s  .c o m
public Object unmarshall(SerializerState state, Class clazz, Object o) throws UnmarshallException {
    Map map = null;
    try {
        try {
            try {
                if (clazz.isInterface()) {
                    map = new java.util.HashMap();
                } else
                    map = (Map) clazz.newInstance();
            } catch (ClassCastException cce) {
                throw new UnmarshallException("invalid unmarshalling Class " + cce.getMessage());
            }
        } catch (IllegalAccessException iae) {
            throw new UnmarshallException("no access unmarshalling object " + iae.getMessage());
        }
    } catch (InstantiationException ie) {
        throw new UnmarshallException("unable to instantiate unmarshalling object " + ie.getMessage());
    }
    JSONObject jso = (JSONObject) o;
    Iterator keys = jso.keys();
    state.setSerialized(o, map);
    try {
        while (keys.hasNext()) {
            String key = (String) keys.next();
            map.put(key, ser.unmarshall(state, null, jso.get(key)));
        }
    } catch (JSONException je) {
        throw new UnmarshallException("Could not read map: " + je.getMessage());
    }

    return map;
}

From source file:edu.msu.walajahi.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./*ww  w.j  av a 2s  .c  om*/
 */
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) {
            // 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.example.android.popularmoviesist2.data.FetchTrailerMovieTask.java

private String[] getMoviesDataFromJson(String moviesJsonStr) throws JSONException {

    final String JSON_LIST = "results";
    final String JSON_ID = "id";
    final String JSON_KEY = "key";
    final String JSON_NAME = "name";
    final String JSON_SITE = "site";

    urlYoutbe.clear();/*  ww w .  ja v a2 s  .co m*/

    try {
        JSONObject moviesJson = new JSONObject(moviesJsonStr);
        JSONArray moviesArray = moviesJson.getJSONArray(JSON_LIST);

        final String[] result = new String[moviesArray.length()];

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

            JSONObject movie = moviesArray.getJSONObject(i);
            String id = movie.getString(JSON_ID);
            String key = movie.getString(JSON_KEY);
            String name = movie.getString(JSON_NAME);
            String site = movie.getString(JSON_SITE);

            result[i] = key;
        }
        return result;
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
        return null;
    }

}

From source file:com.example.android.popularmoviesist2.data.FetchTrailerMovieTask.java

@Override
protected String[] doInBackground(String... params) {

    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;
    movieId = params[0];//w  w w.  java 2s.  co  m

    String moviesJsonStr = null;

    final String MOVIE_VIDEO_URL = "http://api.themoviedb.org/3/movie/" + movieId + "/videos";

    final String APIKEY_PARAM = "api_key";

    try {
        Uri builtUri = Uri.parse(MOVIE_VIDEO_URL).buildUpon()
                .appendQueryParameter(APIKEY_PARAM, BuildConfig.OPEN_TMDB_MAP_API_KEY).build();

        URL url = new URL(builtUri.toString());

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            return null;
        }

        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            return null;
        }

        moviesJsonStr = buffer.toString();
        return getMoviesDataFromJson(moviesJsonStr);

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        return null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    return null;
}

From source file:org.openmidaas.library.authentication.AuthCallbackForAccessToken.java

@Override
public void onSuccess(final String deviceToken) {
    try {/*w  w w  .j  a  v a  2  s . co m*/
        obtainAccessToken(mSubjectToken, deviceToken);
    } catch (JSONException e) {
        MIDaaS.logError(TAG, e.getMessage());
        mCallback.onError(new MIDaaSException(MIDaaSError.INTERNAL_LIBRARY_ERROR));
    }
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public KeywordMapping(String mapFN) {
    file = new File(mapFN);

    // try to load the file, but it's OK if it fails
    JSONObject json = null;//from w w  w  . j  ava  2  s .c o  m
    try {
        Reader rdr = new FileReader(file);
        json = new JSONObject(new JSONTokener(rdr));
        rdr.close();
    } catch (JSONException ex) {
        Util.writeln("NOTE: reading file " + file.getAbsolutePath() + " failed: " + ex.getMessage());
    } catch (IOException ex) {
        return;
    } // includes file not found, which is OK

    try {
        for (JSONObject obj : json.optJSONArrayEmpty("identifiers").toObjectArray()) {
            Identifier id = new Identifier();
            id.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            id.prefix = obj.optString("prefix");
            identifiers.add(id);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("textBlocks").toObjectArray()) {
            TextBlock txt = new TextBlock();
            txt.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            txt.title = obj.optString("title");
            textBlocks.add(txt);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("properties").toObjectArray()) {
            Property prop = new Property();
            prop.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            prop.propURI = obj.optString("propURI");
            prop.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            properties.add(prop);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("values").toObjectArray()) {
            Value val = new Value();
            val.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            val.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            val.valueURI = obj.optString("valueURI");
            val.propURI = obj.optString("propURI");
            val.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            values.add(val);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("literals").toObjectArray()) {
            Literal lit = new Literal();
            lit.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            lit.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            lit.propURI = obj.optString("propURI");
            lit.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            literals.add(lit);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("references").toObjectArray()) {
            Reference ref = new Reference();
            ref.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            ref.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            ref.prefix = obj.optString("prefix");
            ref.propURI = obj.optString("propURI");
            ref.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            references.add(ref);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("assertions").toObjectArray()) {
            Assertion asrt = new Assertion();
            asrt.propURI = obj.optString("propURI");
            asrt.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            asrt.valueURI = obj.optString("valueURI");
            assertions.add(asrt);
        }
    } catch (JSONException ex) {
        Util.writeln("NOTE: parsing error");
        ex.printStackTrace();
        Util.writeln(
                "*** Execution will continue, but part of the mapping has not been loaded and may be overwritten.");
    }
}