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:org.stockchart.series.SeriesBase.java

public void fromJSONObject(JSONObject j) throws JSONException {
    fName = j.getString("name");
    fIndexOffset = j.getInt("indexOffset");
    fXAxisSide = Axis.Side.valueOf(j.getString("xAxisSide"));
    fYAxisSide = Axis.Side.valueOf(j.getString("yAxisSide"));
    fIsVisible = j.getBoolean("visible");

    fLastValue = j.has("lastValue") ? j.getDouble("lastValue") : Double.NaN;
}

From source file:com.webXells.ImageResizer.ImageResizePlugin.java

@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
    JSONObject params;
    String imageData;//from  w ww  .j  av  a2s.  c o m
    String imageDataType;
    String format;
    Bitmap bmp;
    Log.d("PLUGIN", action);
    try {
        // parameters (forst object of the json array)
        params = data.getJSONObject(0);
        // image data, either base64 or url
        imageData = params.getString("data");
        // which data type is that, defaults to base64
        imageDataType = params.has("imageDataType") ? params.getString("imageDataType")
                : DEFAULT_IMAGE_DATA_TYPE;
        // which format should be used, defaults to jpg
        format = params.has("format") ? params.getString("format") : DEFAULT_FORMAT;
        // create the Bitmap object, needed for all functions
        bmp = getBitmap(imageData, imageDataType);
    } catch (JSONException e) {
        callbackContext.error(e.getMessage());
        return false;
    } catch (IOException e) {
        callbackContext.error(e.getMessage());
        return false;
    }
    // resize the image
    Log.d("PLUGIN", "passed init");
    if (action.equals("resizeImage")) {
        try {
            double widthFactor;
            double heightFactor;

            // compression quality
            int quality = params.getInt("quality");

            // Pixels or Factor resize
            String resizeType = params.getString("resizeType");

            // Get width and height parameters
            double width = params.getDouble("width");
            double height = params.getDouble("height");

            if (resizeType.equals(RESIZE_TYPE_PIXEL)) {
                widthFactor = width / ((double) bmp.getWidth());
                heightFactor = height / ((double) bmp.getHeight());
            } else {
                widthFactor = width;
                heightFactor = height;
            }

            Bitmap resized = getResizedBitmap(bmp, (float) widthFactor, (float) heightFactor);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (format.equals(FORMAT_PNG)) {
                resized.compress(Bitmap.CompressFormat.PNG, quality, baos);
            } else {
                resized.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            }
            byte[] b = baos.toByteArray();
            String returnString = Base64.encodeToString(b, Base64.DEFAULT);
            // return object
            JSONObject res = new JSONObject();
            res.put("imageData", returnString);
            res.put("width", resized.getWidth());
            res.put("height", resized.getHeight());
            callbackContext.success(res);
            return true;
        } catch (JSONException e) {
            callbackContext.error(e.getMessage());
            return false;
        }
    } else if (action.equals("imageSize")) {
        try {

            JSONObject res = new JSONObject();
            res.put("width", bmp.getWidth());
            res.put("height", bmp.getHeight());
            Log.d("PLUGIN", "finished get image size");
            callbackContext.success(res);
            return true;
        } catch (JSONException e) {
            callbackContext.error(e.getMessage());
            return false;
        }
    } else if (action.equals("storeImage")) {
        try {
            // Obligatory Parameters, throw JSONException if not found
            String filename = params.getString("filename");
            filename = (filename.contains(".")) ? filename : filename + "." + format;
            String directory = params.getString("directory");
            directory = directory.startsWith("/") ? directory : "/" + directory;
            int quality = params.getInt("quality");

            OutputStream outStream;
            // store the file locally using the external storage directory
            File file = new File(Environment.getExternalStorageDirectory().toString() + directory, filename);
            try {
                outStream = new FileOutputStream(file);
                if (format.equals(FORMAT_PNG)) {
                    bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream);
                } else {
                    bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
                }
                outStream.flush();
                outStream.close();
                JSONObject res = new JSONObject();
                res.put("url", "file://" + file.getAbsolutePath());
                callbackContext.success(res);
                return true;
            } catch (IOException e) {
                callbackContext.error(e.getMessage());
                return false;
            }
        } catch (JSONException e) {
            callbackContext.error(e.getMessage());
            return false;
        }
    }
    Log.d("PLUGIN", "unknown action");
    return false;
}

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

protected void FillData(int nType, String sJSON) {
    GetDataStoped();//w w w  .  j  a va2s  . co  m
    try {
        JSONObject jsonMainObject = new JSONObject(sJSON);
        if (jsonMainObject.getBoolean("error")) {
            String sMsg = jsonMainObject.getString("msg");
            SendError(sMsg);
            return;
        }

        if (jsonMainObject.has("rows") && !jsonMainObject.isNull("rows")) {

            JSONArray jsonArray = jsonMainObject.getJSONArray("rows");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                //Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
                long nId = jsonObject.getLong("fid");

                long nKey = 10000000000L * nType + nId; //as we have values from separte tables we can get same key - to prevent this add big value multiplied on source type
                if (mmoFires.containsKey(nKey))
                    continue;

                int nIconId = 0;
                if (nType == 1) {//user
                    nIconId = R.drawable.ic_eye;
                } else if (nType == 2) {//nasa
                    nIconId = R.drawable.ic_nasa;
                }

                String sDate = jsonObject.getString("date");
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date dtFire = dateFormat.parse(sDate);
                double dfLat = jsonObject.getDouble("lat");
                double dfLon = jsonObject.getDouble("lon");
                double dfDist = jsonObject.getDouble("dist");

                FireItem item = new FireItem(this, nType, nId, dtFire, dfLon, dfLat, dfDist, nIconId);
                mmoFires.put(nKey, item);

                SendItem(item);
                String sMsg = String.format("%s/%.1f %s/%s", item.GetShortCoordinates(), dfDist / 1000,
                        getString(R.string.km), item.GetDateAsString());
                onNotify(nType, sMsg);
            }
        }
    } catch (Exception e) {
        SendError(e.getLocalizedMessage());//         e.printStackTrace();
    }
}

From source file:net.bither.api.GetExchangeTickerApi.java

@Override
public void setResult(String response) throws Exception {
    JSONObject json = new JSONObject(response);
    LogUtil.d("http", getUrl() + "," + response);
    this.mCurrencyRate = json.getDouble(CURRENCY_RATE);
    this.result = Ticker.formatList(json);
}

From source file:com.soomla.store.domain.data.VirtualCurrencyPack.java

/** Constructor
 *
 * Generates an instance of {@link VirtualCurrencyPack} from a JSONObject.
 * @param jsonObject is a JSONObject representation of the wanted {@link VirtualCurrencyPack}.
 * @throws JSONException/*from   w  ww. j  a  v  a2 s . com*/
 */
public VirtualCurrencyPack(JSONObject jsonObject) throws JSONException {
    super(jsonObject);
    try {
        this.mGoogleItem = new GoogleMarketItem(jsonObject.getString(JSONConsts.CURRENCYPACK_PRODUCT_ID),
                GoogleMarketItem.Managed.UNMANAGED);
        this.mPrice = jsonObject.getDouble(JSONConsts.CURRENCYPACK_PRICE);
        this.mCurrencyAmount = jsonObject.getInt(JSONConsts.CURRENCYPACK_AMOUNT);
        this.mCurrency = StoreInfo.getInstance()
                .getVirtualCurrencyByItemId(jsonObject.getString(JSONConsts.CURRENCYPACK_CURRENCYITEMID));
    } catch (VirtualItemNotFoundException e) {
        if (StoreConfig.debug) {
            Log.d(TAG, "Couldn't find the associated currency.");
        }
    }
}

From source file:com.nextgis.maplib.display.SimpleMarkerStyle.java

@Override
public void fromJSON(JSONObject jsonObject) throws JSONException {
    super.fromJSON(jsonObject);
    mOutColor = jsonObject.getInt(JSON_OUTCOLOR_KEY);
    mType = jsonObject.getInt(JSON_TYPE_KEY);
    mWidth = (float) jsonObject.getDouble(JSON_WIDTH_KEY);
    mSize = (float) jsonObject.getDouble(JSON_SIZE_KEY);
}

From source file:tritop.android.naturalselectionnews.StatsWorker.java

private boolean parseWarJSON(String json) {
    if (json != null) {
        try {//from w w  w.  j  a v  a2s  .com
            JSONArray jsonArray = new JSONArray(json);
            synchronized (dbHelper) {
                dbHelper.beginBulkWork();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject obj = jsonArray.getJSONObject(i);
                    long date = obj.getLong(DBHelper.WAR_STATS_DATA_DATE);
                    String map = obj.getString(DBHelper.WAR_STATS_DATA_MAP);
                    double length = obj.getDouble(DBHelper.WAR_STATS_DATA_LENGTH);
                    int winner = obj.getInt(DBHelper.WAR_STATS_DATA_WINNER);
                    double version = obj.getDouble(DBHelper.WAR_STATS_DATA_VERSION);
                    dbHelper.insertBulkWarStatsValues(date, map, length, winner, version);
                }
                dbHelper.endBulkWork();
            }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }
    return false;
}

From source file:org.n52.geoar.data.wiki.WikiResponse.java

static List<WikiResult> getWikiresultsFromResponse(InputStream content) throws IOException {

    List<WikiResult> resultList = new ArrayList<WikiResult>();

    BufferedReader streamReader = new BufferedReader(new InputStreamReader(content, "UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;//from   w  ww  .  j a v  a  2s  .co  m
    while ((inputStr = streamReader.readLine()) != null)
        responseStrBuilder.append(inputStr);

    try {
        JSONObject root = new JSONObject(responseStrBuilder.toString());
        JSONArray dataArray = root.getJSONArray("articles");

        for (int i = 0, length = dataArray.length(); i < length; i++) {
            JSONObject wikiObject = dataArray.getJSONObject(i);
            WikiResult wr = null;
            if (wikiObject.has(ATTRIB_TITLE) && wikiObject.has(ATTRIB_LAT) && wikiObject.has(ATTRIB_LON)) {
                wr = new WikiResult(wikiObject.getString(ATTRIB_ID), wikiObject.getString(ATTRIB_TITLE),
                        wikiObject.getDouble(ATTRIB_LAT), wikiObject.getDouble(ATTRIB_LON));

                // FIXME make altitude still a parameter
                //               if (wikiObject.has(ATTRIB_ALT))
                //                  wr.setAltitude(wikiObject.getInt(ATTRIB_ALT));

                /** requesting mobile version of website */
                if (wikiObject.has(ATTRIB_URL)) {
                    String url = wikiObject.getString(ATTRIB_URL);
                    int splitIndex = url.indexOf('.');
                    String first = url.substring(0, splitIndex);
                    String last = url.substring(splitIndex + 1, url.length());
                    wr.setUrl(first + ".m." + last);
                }
                resultList.add(wr);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return resultList;
}

From source file:br.unicamp.busfinder.ServerOperations.java

public static ListPoints updateBusPositions(Context c, MapView map, ListPoints realBus) {

    Log.d("Updating Bus Posisionts ...", "");

    realBus.clear();//  w ww .j a  v  a 2  s.  c o  m

    String req = BusFinderActivity.SERVER + "getBusesPositions";
    JSONArray jar = getJSON(req);
    try {

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

            JSONObject bus = jar.getJSONObject(i);

            GeoPoint gP = new GeoPoint((int) (bus.getDouble("latitude") * 1e6),
                    (int) (bus.getDouble("longitude") * 1e6));
            //GeoPoint gP2 = new GeoPoint(
            //   (int) (bus2.getDouble("latitude") * 1e6),
            //(int) (bus2.getDouble("longitude") * 1e6));
            String placa = bus.getString("licensePlate");
            //String placa2 = bus2.getString("licensePlate");

            Log.d(placa, gP.toString());

            //BusFinderActivity.
            //BusFinderActivity.
            realBus.insertPinpoint(new PItem(gP, "bus1", placa));
            //BusFinderActivity.
            //realBus.insertPinpoint(new PItem(gP2, "bus2",
            //   placa2));

            //BusFinderActivity.map.invalidate();
            // map.getController().animateTo(gP2);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return realBus;
}

From source file:a122016.rr.com.alertme.QueryUtilsPoliceStation.java

/**
 * Return a {@link PoliceStation} object that has been built up from
 * parsing the given JSON response./*from ww  w .  ja va 2  s.  co  m*/
 */
private static ArrayList<PoliceStation> extractFeatureFromJson(String PoliceStationsJSON) {

    // If the JSON string is empty or null, then return early.
    if (TextUtils.isEmpty(PoliceStationsJSON)) {
        return null;
    }

    // Create an array list of PoliceStations
    ArrayList<PoliceStation> PoliceStationsList = new ArrayList<PoliceStation>();

    // Try to parse the JSON response string. If there's a problem with the way the JSON
    // is formatted, a JSONException exception object will be thrown.
    // Catch the exception so the app doesn't crash, and print the error message to the logs.
    try {

        // Create a JSONArray from the JSON response string
        JSONArray PoliceStationArray = new JSONArray(PoliceStationsJSON);

        // For each PoliceStation in the PoliceStationArray, create an {@link PoliceStation} object
        for (int i = 0; i < PoliceStationArray.length(); i++) {

            // Get a single PoliceStation at position i within the list of PoliceStations
            JSONObject currentPoliceStation = PoliceStationArray.getJSONObject(i);

            // Extract the value for the key called "Name"
            String name = currentPoliceStation.getString("Name");

            // Extract the value for the key called "Number"
            String number = currentPoliceStation.getString("Number");

            double latitude = currentPoliceStation.getDouble("Latitude");
            double longitude = currentPoliceStation.getDouble("Longitude");

            // Create a new {@link PoliceStation} object
            PoliceStation PoliceStation = new PoliceStation(name, number, latitude, longitude);

            // Add the new {@link PoliceStation} to the list of PoliceStations.
            PoliceStationsList.add(PoliceStation);
        }

    } catch (JSONException e) {
        // If an error is thrown when executing any of the above statements in the "try" block,
        // catch the exception here, so the app doesn't crash. Print a log message
        // with the message from the exception.
        Log.e("QueryUtilsPoliceStation", "Problem parsing the PoliceStations JSON results", e);
    }

    // Return the array list
    return PoliceStationsList;
}