Example usage for org.json JSONObject getDouble

List of usage examples for org.json JSONObject getDouble

Introduction

In this page you can find the example usage for org.json JSONObject getDouble.

Prototype

public double getDouble(String key) throws JSONException 

Source Link

Document

Get the double value associated with a key.

Usage

From source file:com.foxykeep.datadroidpoc.data.factory.PhoneListFactory.java

public static ArrayList<Phone> parseResult(String wsResponse) throws DataException {
    ArrayList<Phone> phoneList = new ArrayList<Phone>();

    try {/*from   w  ww . ja v a  2 s.c om*/
        JSONObject parser = new JSONObject(wsResponse);
        JSONObject jsonRoot = parser.getJSONObject(JSONTag.CRUD_PHONE_LIST_ELEM_PHONES);
        JSONArray jsonPhoneArray = jsonRoot.getJSONArray(JSONTag.CRUD_PHONE_LIST_ELEM_PHONE);
        int size = jsonPhoneArray.length();
        for (int i = 0; i < size; i++) {
            JSONObject jsonPhone = jsonPhoneArray.getJSONObject(i);
            Phone phone = new Phone();

            phone.serverId = jsonPhone.getLong(JSONTag.CRUD_PHONE_LIST_ELEM_ID);
            phone.name = jsonPhone.getString(JSONTag.CRUD_PHONE_LIST_ELEM_NAME);
            phone.manufacturer = jsonPhone.getString(JSONTag.CRUD_PHONE_LIST_ELEM_MANUFACTURER);
            phone.androidVersion = jsonPhone.getString(JSONTag.CRUD_PHONE_LIST_ELEM_ANDROID_VERSION);
            phone.screenSize = jsonPhone.getDouble(JSONTag.CRUD_PHONE_LIST_ELEM_SCREEN_SIZE);
            phone.price = jsonPhone.getInt(JSONTag.CRUD_PHONE_LIST_ELEM_PRICE);

            phoneList.add(phone);
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
        throw new DataException(e);
    }

    return phoneList;
}

From source file:com.nextgis.firereporter.ScanexNotificationItem.java

public ScanexNotificationItem(Context c, JSONObject object) {
    Prepare(c);/*from  ww w  .  ja va  2s  .c o  m*/
    try {
        this.nID = object.getLong("id");
        this.dt = new Date(object.getLong("date"));
        this.X = object.getDouble("X");
        this.Y = object.getDouble("Y");
        this.nConfidence = object.getInt("confidence");
        this.nPower = object.getInt("power");
        this.sURL1 = object.getString("URL1");
        this.sURL2 = object.getString("URL2");
        this.sType = object.getString("type");
        this.sPlace = object.getString("place");
        this.sMap = object.getString("map");
        this.nIconId = object.getInt("iconId");
        this.mbWatched = object.getBoolean("watched");

    } catch (JSONException e) {
        SendError(e.getLocalizedMessage());
    }

}

From source file:com.textuality.lifesaver.Columns.java

private static void j2cvFloat(JSONObject j, ContentValues cv, String key) {
    try {//  w ww  .j a v  a  2s .  c  om
        float v = (float) j.getDouble(key);
        cv.put(key, v);
    } catch (JSONException e) {
    }
}

From source file:com.textuality.lifesaver.Columns.java

private static void j2cvDouble(JSONObject j, ContentValues cv, String key) {
    try {/*from w w  w . jav a2s.c  om*/
        double v = j.getDouble(key);
        cv.put(key, v);
    } catch (JSONException e) {
    }
}

From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent == null) {
        return;/*from  w  w w  .  j a  va  2 s. co m*/
    }
    final boolean force = intent.getBooleanExtra("force", false);
    try {
        Locale loc = Locale.getDefault();
        String lang = loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php; T-values if present both T and B
        if (lang == null || lang.length() == 0) {
            lang = "";
        }

        int serverVersion = intent.getIntExtra("serverVersion", -1);
        boolean fromPush = serverVersion != -1;
        JSONObject versionJson = null;
        if (!fromPush) {
            versionJson = getVersion(true);
            serverVersion = versionJson.getInt("version");
        }
        int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1);
        final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, "");

        if (serverVersion <= localVersion && !force && lang.equals(localLanguage)
                && !LOCAL_DEFINITION_TESTING) {
            // don't update
            DebugLog.i("Nothing new, not updating");
            return;
        }

        // update but don't notify about it.
        boolean firstLaunchNoUpdate = ((localVersion == -1
                && getVersion(false).getInt("version") == serverVersion) || !lang.equals(localLanguage));

        if (!firstLaunchNoUpdate) {
            DebugLog.i("There are new definitions available!");
        }

        handleAuthorMessage(versionJson, lang, intent, fromPush);

        InputStream is = getIS(URL_TICKETS_ID);
        try {
            String json = readResult(is);

            JSONObject o = new JSONObject(json);
            JSONArray array = o.getJSONArray("tickets");

            final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase();
            for (int i = 0; i < array.length(); i++) {
                final JSONObject city = array.getJSONObject(i);
                try {

                    final ContentValues cv = new ContentValues();
                    cv.put(Cities._ID, city.getInt("id"));
                    cv.put(Cities.CITY, getStringLocValue(city, lang, "city"));
                    if (city.has("city_pubtran")) {
                        cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran"));
                    }
                    cv.put(Cities.COUNTRY, city.getString("country"));
                    cv.put(Cities.CURRENCY, city.getString("currency"));
                    cv.put(Cities.DATE_FORMAT, city.getString("dateFormat"));
                    cv.put(Cities.IDENTIFICATION, city.getString("identification"));
                    cv.put(Cities.LAT, city.getDouble("lat"));
                    cv.put(Cities.LON, city.getDouble("lon"));
                    cv.put(Cities.NOTE, getStringLocValue(city, lang, "note"));
                    cv.put(Cities.NUMBER, city.getString("number"));
                    cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom"));
                    cv.put(Cities.P_DATE_TO, city.getString("pDateTo"));
                    cv.put(Cities.P_HASH, city.getString("pHash"));
                    cv.put(Cities.PRICE, city.getString("price"));
                    cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote"));
                    cv.put(Cities.REQUEST, city.getString("request"));
                    cv.put(Cities.VALIDITY, city.getInt("validity"));
                    if (city.has("confirmReq")) {
                        cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq"));
                    }
                    if (city.has("confirm")) {
                        cv.put(Cities.CONFIRM, city.getString("confirm"));
                    }

                    final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers");
                    for (int j = 0; j < additionalNumbers.length() && j < 3; j++) {
                        cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j));
                    }

                    db.beginTransaction();
                    int count = db.update(DatabaseHelper.CITY_TABLE_NAME, cv,
                            Cities._ID + " = " + cv.getAsInteger(Cities._ID), null);
                    if (count == 0) {
                        db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv);
                    }

                    db.setTransactionSuccessful();
                    getContentResolver().notifyChange(Cities.CONTENT_URI, null);
                } finally {
                    if (db.inTransaction()) {
                        db.endTransaction();
                    }
                }
            }
            Preferences.set(c, Preferences.DATA_VERSION, serverVersion);
            Preferences.set(c, Preferences.DATA_LANGUAGE, lang);
            if (!firstLaunchNoUpdate && !fromPush) {
                final int finalServerVersion = serverVersion;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UpdateService.this,
                                getString(R.string.cities_update_completed, finalServerVersion),
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
            if (LOCAL_DEFINITION_TESTING) {
                DebugLog.w(
                        "Local definition testing - data updated from assets - must be removed in production!");
            }
        } finally {
            is.close();
        }
    } catch (IOException e) {
        DebugLog.e("IOException when calling update: " + e.getMessage(), e);
    } catch (JSONException e) {
        DebugLog.e("JSONException when calling update: " + e.getMessage(), e);
    }
}

From source file:com.goliathonline.android.kegbot.io.RemoteKegHandler.java

/** {@inheritDoc} */
@Override/*from   w  ww .j  a  v  a  2s. c  o  m*/
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    // Walk document, parsing any incoming entries
    JSONObject result = parser.getJSONObject("result");
    JSONObject keg = result.getJSONObject("keg");
    JSONObject type = result.getJSONObject("type");
    JSONObject image = type.getJSONObject("image");

    final String kegId = sanitizeId(keg.getString("id"));
    final Uri kegUri = Kegs.buildKegUri(kegId);

    // Check for existing details, only update when changed
    final ContentValues values = queryKegDetails(kegUri, resolver);
    final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
    final long serverUpdated = 500; //entry.getUpdated();
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "found keg " + kegId);
        Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
    }

    // Clear any existing values for this session, treating the
    // incoming details as authoritative.
    batch.add(ContentProviderOperation.newDelete(kegUri).build());

    final ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Kegs.CONTENT_URI);

    builder.withValue(SyncColumns.UPDATED, serverUpdated);
    builder.withValue(Kegs.KEG_ID, kegId);

    // Inherit starred value from previous row
    if (values.containsKey(Kegs.KEG_STARRED)) {
        builder.withValue(Kegs.KEG_STARRED, values.getAsInteger(Kegs.KEG_STARRED));
    }

    if (keg.has("status"))
        builder.withValue(Kegs.STATUS, keg.getString("status"));

    if (keg.has("volume_ml_remain"))
        builder.withValue(Kegs.VOLUME_REMAIN, keg.getDouble("volume_ml_remain"));

    if (keg.has("description"))
        builder.withValue(Kegs.DESCRIPTION, keg.getString("description"));

    if (keg.has("type_id"))
        builder.withValue(Kegs.TYPE_ID, keg.getString("type_id"));

    if (keg.has("size_id"))
        builder.withValue(Kegs.SIZE_ID, keg.getInt("size_id"));

    if (keg.has("percent_full"))
        builder.withValue(Kegs.PERCENT_FULL, keg.getDouble("percent_full"));

    if (keg.has("size_name"))
        builder.withValue(Kegs.SIZE_NAME, keg.getString("size_name"));

    if (keg.has("spilled_ml"))
        builder.withValue(Kegs.VOLUME_SPILL, keg.getDouble("spilled_ml"));

    if (keg.has("size_volume_ml"))
        builder.withValue(Kegs.VOLUME_SIZE, keg.getDouble("size_volume_ml"));

    if (type.has("name"))
        builder.withValue(Kegs.KEG_NAME, type.getString("name"));

    if (type.has("abv"))
        builder.withValue(Kegs.KEG_ABV, type.getDouble("abv"));

    if (image.has("url"))
        builder.withValue(Kegs.IMAGE_URL, image.getString("url"));

    // Normal keg details ready, write to provider
    batch.add(builder.build());

    return batch;
}

From source file:com.ecofactor.qa.automation.newapp.service.BaseDataServiceImpl.java

/**
 * Creates the algo control list./* www.j  a va2 s. c o m*/
 * @param jobData the job data
 * @param thermostatId the thermostat id
 * @param algoId the algo id
 * @return the list
 */
protected List<ThermostatAlgorithmController> createAlgoControlList(JSONArray jobData, Integer thermostatId,
        Integer algoId) {

    Algorithm algorithm = findByAlgorithmId(algoId);
    List<ThermostatAlgorithmController> algoControlList = new ArrayList<ThermostatAlgorithmController>();

    int moBlackOut;
    double moRecovery;
    double deltaEE = 0;
    Calendar utcCalendar = null;
    Calendar startTime = null;
    Calendar endTime = null;
    Calendar moCutoffTime = null;
    JSONObject jsonObj;

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

        try {

            jsonObj = jobData.getJSONObject(i);
            startTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("start"));
            endTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("end"));
            moCutoffTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("moCutoff"));

            moBlackOut = jsonObj.getInt("moBlackOut");
            moRecovery = jsonObj.getInt("moRecovery");
            deltaEE = jsonObj.getDouble("deltaEE");

            ThermostatAlgorithmController algoControlPhase1 = new ThermostatAlgorithmController();
            algoControlPhase1.setStatus(Status.ACTIVE);
            algoControlPhase1.setThermostatId(thermostatId);
            algoControlPhase1.setAlgorithmId(algoId);

            String utcCalendarTimeStamp = DateUtil.format(startTime, DateUtil.DATE_FMT_FULL);
            utcCalendar = DateUtil.parseToCalendar(utcCalendarTimeStamp, DateUtil.DATE_FMT_FULL);

            // Next phase time
            algoControlPhase1.setNextPhaseTime(utcCalendar);

            // Execution start time.
            Calendar executionStartTime = (Calendar) utcCalendar.clone();
            executionStartTime.add(Calendar.MINUTE, -3);
            algoControlPhase1.setExecutionStartTimeUTC(executionStartTime);

            String endutcCalendarTimeStamp = DateUtil.format(endTime, DateUtil.DATE_FMT_FULL);
            Calendar endutcCalendar = DateUtil.parseToCalendar(endutcCalendarTimeStamp, DateUtil.DATE_FMT_FULL);

            // Execution end time.
            algoControlPhase1.setExecutionEndTimeUTC(endutcCalendar);

            String cuttoffutcCalendarTimeStamp = DateUtil.format(moCutoffTime, DateUtil.DATE_FMT_FULL);
            Calendar cutOffutcCalendar = DateUtil.parseToCalendar(cuttoffutcCalendarTimeStamp,
                    DateUtil.DATE_FMT_FULL);

            // MO cut off time.
            algoControlPhase1.setMoCutOff(cutOffutcCalendar);

            algoControlPhase1.setPhase0Spt(deltaEE);
            algoControlPhase1.setPrevSpt(0.0);
            algoControlPhase1.setMoBlackOut(moBlackOut);
            algoControlPhase1.setMoRecovery(moRecovery);
            algoControlPhase1.setAlgorithm(algorithm);
            if (algoId == SPO_COOL || algoId == SPO_HEAT) {
                algoControlPhase1.setActor(ACTOR_SPO);
            }

            algoControlList.add(algoControlPhase1);
            // second row
            ThermostatAlgorithmController algoControlPhase2 = new ThermostatAlgorithmController();

            algoControlPhase2 = algoControlPhase1.clone();

            endutcCalendarTimeStamp = DateUtil.format(endTime, DateUtil.DATE_FMT_FULL);
            endutcCalendar = DateUtil.parseToCalendar(endutcCalendarTimeStamp, DateUtil.DATE_FMT_FULL);

            if (algoId == SPO_COOL || algoId == SPO_HEAT) {
                algoControlPhase2.setActor(ACTOR_SPO);
            }
            // Execution end time.
            algoControlPhase2.setExecutionStartTimeUTC(endutcCalendar);
            algoControlPhase2.setExecutionEndTimeUTC(null);
            algoControlPhase2.setNextPhaseTime(endutcCalendar);
            algoControlPhase2.setPhase0Spt(0.0);
            algoControlPhase2.setAlgorithm(algorithm);
            algoControlPhase2.setStatus(Status.ACTIVE);
            algoControlList.add(algoControlPhase2);

        } catch (JSONException | CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
    return algoControlList;
}

From source file:com.trk.aboutme.facebook.SharedPreferencesTokenCachingStrategy.java

private void deserializeKey(String key, Bundle bundle) throws JSONException {
    String jsonString = cache.getString(key, "{}");
    JSONObject json = new JSONObject(jsonString);

    String valueType = json.getString(JSON_VALUE_TYPE);

    if (valueType.equals(TYPE_BOOLEAN)) {
        bundle.putBoolean(key, json.getBoolean(JSON_VALUE));
    } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        boolean[] array = new boolean[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getBoolean(i);
        }/* ww w  .j a v  a2s . co  m*/
        bundle.putBooleanArray(key, array);
    } else if (valueType.equals(TYPE_BYTE)) {
        bundle.putByte(key, (byte) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_BYTE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        byte[] array = new byte[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (byte) jsonArray.getInt(i);
        }
        bundle.putByteArray(key, array);
    } else if (valueType.equals(TYPE_SHORT)) {
        bundle.putShort(key, (short) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_SHORT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        short[] array = new short[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (short) jsonArray.getInt(i);
        }
        bundle.putShortArray(key, array);
    } else if (valueType.equals(TYPE_INTEGER)) {
        bundle.putInt(key, json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int[] array = new int[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getInt(i);
        }
        bundle.putIntArray(key, array);
    } else if (valueType.equals(TYPE_LONG)) {
        bundle.putLong(key, json.getLong(JSON_VALUE));
    } else if (valueType.equals(TYPE_LONG_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        long[] array = new long[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getLong(i);
        }
        bundle.putLongArray(key, array);
    } else if (valueType.equals(TYPE_FLOAT)) {
        bundle.putFloat(key, (float) json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        float[] array = new float[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (float) jsonArray.getDouble(i);
        }
        bundle.putFloatArray(key, array);
    } else if (valueType.equals(TYPE_DOUBLE)) {
        bundle.putDouble(key, json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        double[] array = new double[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getDouble(i);
        }
        bundle.putDoubleArray(key, array);
    } else if (valueType.equals(TYPE_CHAR)) {
        String charString = json.getString(JSON_VALUE);
        if (charString != null && charString.length() == 1) {
            bundle.putChar(key, charString.charAt(0));
        }
    } else if (valueType.equals(TYPE_CHAR_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        char[] array = new char[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            String charString = jsonArray.getString(i);
            if (charString != null && charString.length() == 1) {
                array[i] = charString.charAt(0);
            }
        }
        bundle.putCharArray(key, array);
    } else if (valueType.equals(TYPE_STRING)) {
        bundle.putString(key, json.getString(JSON_VALUE));
    } else if (valueType.equals(TYPE_STRING_LIST)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int numStrings = jsonArray.length();
        ArrayList<String> stringList = new ArrayList<String>(numStrings);
        for (int i = 0; i < numStrings; i++) {
            Object jsonStringValue = jsonArray.get(i);
            stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue);
        }
        bundle.putStringArrayList(key, stringList);
    } else if (valueType.equals(TYPE_ENUM)) {
        try {
            String enumType = json.getString(JSON_VALUE_ENUM_TYPE);
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType);
            @SuppressWarnings("unchecked")
            Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE));
            bundle.putSerializable(key, enumValue);
        } catch (ClassNotFoundException e) {
        } catch (IllegalArgumentException e) {
        }
    }
}

From source file:com.ultramegatech.ey.UpdateService.java

/**
 * Add a value from a JSONObject to a ContentValues object in the appropriate data type.
 * //ww w.j  av a2 s .c o m
 * @param to
 * @param from
 * @param key The key of the entry to process
 * @throws JSONException 
 */
private static void addValue(ContentValues to, JSONObject from, String key) throws JSONException {
    switch (Elements.getColumnType(key)) {
    case INTEGER:
    case BOOLEAN:
        to.put(key, from.getInt(key));
        break;
    case REAL:
        to.put(key, from.getDouble(key));
        break;
    case TEXT:
        to.put(key, from.getString(key));
        break;
    }
}

From source file:org.mixare.data.convert.WikiDataProcessor.java

@Override
public List<Marker> load(String rawData, int taskId, int colour) throws JSONException {
    List<Marker> markers = new ArrayList<Marker>();
    JSONObject root = convertToJSON(rawData);
    JSONArray dataArray = root.getJSONArray("geonames");
    int top = Math.min(MAX_JSON_OBJECTS, dataArray.length());

    for (int i = 0; i < top; i++) {
        JSONObject jo = dataArray.getJSONObject(i);

        Marker ma = null;/*from   ww w .  j a  v a  2 s .  com*/
        if (jo.has("title") && jo.has("lat") && jo.has("lng") && jo.has("elevation")
                && jo.has("wikipediaUrl")) {

            Log.v(MixView.TAG, "processing Wikipedia JSON object");

            //no unique ID is provided by the web service according to http://www.geonames.org/export/wikipedia-webservice.html
            ma = new POIMarker("", HtmlUnescape.unescapeHTML(jo.getString("title"), 0), jo.getDouble("lat"),
                    jo.getDouble("lng"), jo.getDouble("elevation"), "http://" + jo.getString("wikipediaUrl"),
                    taskId, colour);
            markers.add(ma);
        }
    }
    return markers;
}