Example usage for org.json JSONObject optDouble

List of usage examples for org.json JSONObject optDouble

Introduction

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

Prototype

public double optDouble(String key, double defaultValue) 

Source Link

Document

Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not a number.

Usage

From source file:com.nascent.android.glass.glasshackto.greenpfinder.model.GreenPSpots.java

/**
 * Converts a JSON object that represents a place into a {@link Place} object.
 *//*  ww  w .jav  a 2 s.c o  m*/
private ParkingLot jsonObjectToParkingLot(JSONObject object) {
    int id = object.optInt("id");
    String name = object.optString("address");
    String rate = object.optString("rate");
    double latitude = object.optDouble("lat", Double.NaN);
    double longitude = object.optDouble("lng", Double.NaN);

    if (!name.isEmpty() && !Double.isNaN(latitude) && !Double.isNaN(longitude)) {
        return new ParkingLot(id, latitude, longitude, name, rate);
    } else {
        return null;
    }
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

/***********************************************************************************************************************************
 * WEB LAYER//from  ww w  . j a v a 2s  . c  o m
 **********************************************************************************************************************************/
private void showWebLayer(JSONObject data) {
    try {
        String page = data.getString(Cobalt.kJSPage);
        double fadeDuration = data.optDouble(Cobalt.kJSWebLayerFadeDuration, 0.3);

        Bundle bundle = new Bundle();
        bundle.putString(Cobalt.kPage, page);

        CobaltWebLayerFragment webLayerFragment = getWebLayerFragment();

        if (webLayerFragment != null) {
            webLayerFragment.setArguments(bundle);

            FragmentTransaction fragmentTransition = ((FragmentActivity) mContext).getSupportFragmentManager()
                    .beginTransaction();

            if (fadeDuration > 0) {
                fragmentTransition.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out,
                        android.R.anim.fade_in, android.R.anim.fade_out);
            } else {
                fragmentTransition.setTransition(FragmentTransaction.TRANSIT_NONE);
            }

            if (CobaltActivity.class.isAssignableFrom(mContext.getClass())) {
                // Dismiss current Web layer if one is already shown
                CobaltActivity activity = (CobaltActivity) mContext;
                Fragment currentFragment = activity.getSupportFragmentManager()
                        .findFragmentById(activity.getFragmentContainerId());
                if (currentFragment != null
                        && CobaltWebLayerFragment.class.isAssignableFrom(currentFragment.getClass())) {
                    ((CobaltWebLayerFragment) currentFragment).dismissWebLayer(null);
                }

                // Shows Web layer
                if (activity.findViewById(activity.getFragmentContainerId()) != null) {
                    fragmentTransition.add(activity.getFragmentContainerId(), webLayerFragment);
                    fragmentTransition.commit();
                } else if (Cobalt.DEBUG)
                    Log.e(Cobalt.TAG, TAG + " - showWebLayer: fragment container not found");
            }
        } else if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - showWebLayer: getWebLayerFragment returned null!");
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - showWebLayer: JSONException");
        exception.printStackTrace();
    }
}

From source file:com.google.blockly.model.FieldNumber.java

public static FieldNumber fromJson(JSONObject json) throws BlockLoadingException {
    String name = json.optString("name", null);
    if (name == null) {
        throw new BlockLoadingException("Number fields must have name field.");
    }//ww  w .  j a v a 2s  . c  o m

    FieldNumber field = new FieldNumber(name);

    if (json.has("value")) {
        try {
            field.setValue(json.getDouble("value"));
        } catch (JSONException e) {
            throw new BlockLoadingException(
                    "Cannot parse field_number value: " + json.optString("value", "[object or array]"));
        }
    }
    try {
        field.setConstraints(json.optDouble("min", NO_CONSTRAINT), json.optDouble("max", NO_CONSTRAINT),
                json.optDouble("precision", NO_CONSTRAINT));
    } catch (IllegalArgumentException e) {
        throw new BlockLoadingException(e);
    }
    return field;
}

From source file:com.richtodd.android.quiltdesign.block.Quilt.java

static final Quilt createFromJSONObject(JSONObject jsonObject) throws JSONException {

    int rowCount = jsonObject.optInt("rowCount", 0);
    int columnCount = jsonObject.optInt("columnCount", 0);
    float width = (float) jsonObject.optDouble("width", 0);
    float height = (float) jsonObject.optDouble("height", 0);

    Quilt quilt = new Quilt(rowCount, columnCount, width, height);

    if (jsonObject.has("quiltBlocks")) {
        JSONArray jsonQuiltBlocks = jsonObject.getJSONArray("quiltBlocks");

        int index = -1;
        for (int row = 0; row < quilt.m_rowCount; ++row) {
            for (int column = 0; column < quilt.m_columnCount; ++column) {
                index += 1;//from w ww  .j  a  v  a 2 s .  c  o m
                if (index < jsonQuiltBlocks.length()) {
                    JSONObject jsonQuiltBlock = jsonQuiltBlocks.optJSONObject(index);
                    if (jsonQuiltBlock != null) {
                        QuiltBlock quiltBlock = QuiltBlock.createFromJSONObject(jsonQuiltBlock);
                        quilt.setQuiltBlock(row, column, quiltBlock);
                    }
                }
            }
        }
    }

    quilt.m_new = false;
    return quilt;
}

From source file:com.marianhello.cordova.bgloc.Config.java

public static Config fromJSONArray(JSONArray data) throws JSONException {
    JSONObject jObject = data.getJSONObject(0);
    Config config = new Config();
    config.setStationaryRadius((float) jObject.optDouble("stationaryRadius", config.getStationaryRadius()));
    config.setDistanceFilter(jObject.optInt("distanceFilter", config.getDistanceFilter()));
    config.setDesiredAccuracy(jObject.optInt("desiredAccuracy", config.getDesiredAccuracy()));
    config.setDebugging(jObject.optBoolean("debug", config.isDebugging()));
    config.setNotificationTitle(jObject.optString("notificationTitle", config.getNotificationTitle()));
    config.setNotificationText(jObject.optString("notificationText", config.getNotificationText()));
    config.setStopOnTerminate(jObject.optBoolean("stopOnTerminate", config.getStopOnTerminate()));
    config.setStartOnBoot(jObject.optBoolean("startOnBoot", config.getStartOnBoot()));
    config.setServiceProvider(jObject.optInt("locationService", config.getServiceProvider().asInt()));
    config.setInterval(jObject.optInt("interval", config.getInterval()));
    config.setFastestInterval(jObject.optInt("fastestInterval", config.getFastestInterval()));
    config.setActivitiesInterval(jObject.optInt("activitiesInterval", config.getActivitiesInterval()));
    config.setNotificationIconColor(/*w w w.j ava 2  s . c o  m*/
            jObject.optString("notificationIconColor", config.getNotificationIconColor()));
    config.setLargeNotificationIcon(
            jObject.optString("notificationIconLarge", config.getLargeNotificationIcon()));
    config.setSmallNotificationIcon(
            jObject.optString("notificationIconSmall", config.getSmallNotificationIcon()));
    config.setStartForeground(jObject.optBoolean("startForeground", config.getStartForeground()));
    config.setUrl(jObject.optString("url", config.getUrl()));
    config.setMethod(jObject.optString("method", config.getMethod()));
    config.setHeaders(jObject.optJSONObject("headers"));
    config.setParams(jObject.optJSONObject("params"));
    return config;
}

From source file:gov.sfmta.sfpark.MyAnnotation.java

public int iconFinder(boolean showPrice) throws JSONException {
    int itemImageName = 0;
    if (onStreet) {
        return itemImageName;
    }/* w  ww . j  ava 2  s .c o m*/

    JSONObject rates = allGarageData.optJSONObject(RATES_KEY);
    String type = allGarageData.optString(TYPE_KEY);
    int used = allGarageData.optInt(OCC_KEY, 0);
    int capacity = allGarageData.optInt(OPER_KEY, 0);
    int avail = capacity - used;
    int availpercent = 0;

    boolean invalidData = true;

    if (capacity == 0) {
        availpercent = 0;
        invalidData = true;
    } else {
        availpercent = Math.round((((float) avail / (float) capacity) * 100) * 10) / 10;
        invalidData = false;
    }

    int usedpercent = 100 - availpercent;

    if (avail < 2 && avail > 0 && availpercent != 0 && capacity <= 3) {
        if (availpercent <= 15) {
            usedpercent = -57; // less than 15 percent available. hack
        } else {
            usedpercent = -58; // more than 15 percent available. hack
        }
    } else if (capacity == 0 && used == 0 && "ON".equals(type)) {
        // On street parking, force it to red as capacity is zero
        usedpercent = -42;
    }

    // since the code above and code below is adapted from
    // two different functions from webmap.js this
    // variable links amountUsed and usedpercent to keep
    // the source code consistent here in the java version
    // where the two functions are basically fused
    // together. This is a hack on a hack. *sigh*
    int amountUsed = usedpercent;
    if (invalidData) {
        itemImageName = invalid_garage;
    } else if (amountUsed > 90 || amountUsed == -42) {
        itemImageName = garage_availability_low;
    } else if ((amountUsed <= 90 && amountUsed >= 70) || amountUsed == -58) {
        itemImageName = garage_availability_medium;
    } else if ((amountUsed < 70 && amountUsed >= 0) || amountUsed == -57) {
        itemImageName = garage_availability_high;
    }

    // modified so that negative available spaces will show as red, not grey:
    if (amountUsed == -1 || amountUsed == -2) {
        itemImageName = invalid_garage;
    }

    // New rule: if available > capacity, show grey not red
    if (avail > capacity)
        itemImageName = invalid_garage;

    // Save garage availability color even if we're on a price page,
    // because we may need it for the details page:
    switch (itemImageName) {
    case garage_availability_high:
        garageColor = availHigh;
        break;
    case garage_availability_medium:
        garageColor = availMed;
        break;
    case garage_availability_low:
        garageColor = availLow;
        break;
    default: // invalid
        garageColor = grey;
        break;
    }

    if (showPrice) {
        if (rates != null) {
            JSONArray rateArray = rates.optJSONArray(RS_KEY);
            if (!(rateArray == null)) {
                boolean isDynamicPricing = true;
                int rsc = rateArray.length();
                for (int i = 0; i < rsc; i++) {
                    JSONObject rateObject = rateArray.getJSONObject(i);
                    float phr = (float) rateObject.optDouble(RATE_KEY, 0);
                    String description = rateObject.optString(DESC_KEY);
                    if (description != null) {
                        if (description.contains(INCREMENTAL_STR)) {
                            itemImageName = nameFinder(phr);
                            isDynamicPricing = false;
                            pricePerHour = phr;
                            break;
                        }
                    }
                }

                if (isDynamicPricing) {
                    for (int i = 0; i < rsc; i++) {
                        JSONObject rateObject = rateArray.getJSONObject(i);
                        float phr = (float) rateObject.optDouble(RATE_KEY, 0);
                        rateStructureHandle(rateObject);
                        if (inThisBucketBegin(beg, end)) {
                            itemImageName = nameFinder(phr);
                            pricePerHour = phr;
                            break;
                        }
                    }
                }
            }
        }
    }
    rateQualifier = rq;
    return itemImageName;
}

From source file:com.phonegap.Capture.java

@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
    this.callbackId = callbackId;
    this.limit = 1;
    this.duration = 0.0f;
    this.results = new JSONArray();

    JSONObject options = args.optJSONObject(0);
    if (options != null) {
        limit = options.optLong("limit", 1);
        duration = options.optDouble("duration", 0.0f);
    }/*from w ww  .j  a v  a2 s .co  m*/

    if (action.equals("getFormatData")) {
        try {
            JSONObject obj = getFormatData(args.getString(0), args.getString(1));
            return new PluginResult(PluginResult.Status.OK, obj);
        } catch (JSONException e) {
            return new PluginResult(PluginResult.Status.ERROR);
        }
    } else if (action.equals("captureAudio")) {
        this.captureAudio();
    } else if (action.equals("captureImage")) {
        this.captureImage();
    } else if (action.equals("captureVideo")) {
        this.captureVideo(duration);
    }

    PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
    r.setKeepCallback(true);
    return r;
}

From source file:net.algart.simagis.live.json.minimal.SimagisLiveUtils.java

public static void standardCustomizePlanePyramidSourceRendering(AbstractPlanePyramidSource source,
        JSONObject renderingJson) {/*from  w  w w  . j  av  a2  s  .  co  m*/
    final JSONObject coarseData = openObject(renderingJson, "coarseData");
    source.setSkipCoarseData(coarseData.optBoolean("skip"));
    source.setSkippingFiller(coarseData.optDouble("filler", 0.0));
}

From source file:org.bd2kccc.bd2kcccpubmed.Crawler.java

boolean isGene(String word) {

    if (true)/*from  w  ww .  j  a v  a2s.  co m*/
        return false;
    //this threshold varies quite a lot, from < 1 to > 400
    double similarityThreshod = 1;

    String mygeneUrl = "http://mygene.info/v2/query?q=";
    HttpRequest request = HttpRequest.get(mygeneUrl + word);
    JSONObject requestJson = new JSONObject(request.body());
    double geneSimilarity = requestJson.optDouble("max_score", 0);

    return geneSimilarity > similarityThreshod;
}

From source file:mobi.carton.glass.model.Landmarks.java

/**
 * Converts a JSON object that represents a place into a {@link Place} object.
 *///from   w  w w.jav  a2  s  . co  m
private Place jsonObjectToPlace(JSONObject object) {
    String name = object.optString("name");
    double latitude = object.optDouble("latitude", Double.NaN);
    double longitude = object.optDouble("longitude", Double.NaN);

    if (!name.isEmpty() && !Double.isNaN(latitude) && !Double.isNaN(longitude)) {
        return new Place(latitude, longitude, name);
    } else {
        return null;
    }
}