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.skalski.raspberrycontrol.Activity_TempSensors.java

Handler getClientHandler() {

    return new Handler() {
        @Override/*from www.  j a v a  2 s. co m*/
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            JSONObject root;
            JSONArray tempsensors;
            tempsensorsArray = new ArrayList<Custom_TempSensorsAdapter>();
            tempsensorsLayout.setRefreshing(false);

            Log.i(LOGTAG, LOGPREFIX + "new message received from server");

            try {

                root = new JSONObject(msg.obj.toString());

                if (root.has(TAG_ERROR)) {

                    String err = getResources().getString(R.string.com_msg_3) + root.getString(TAG_ERROR);
                    toast_connection_error(err);

                } else {

                    tempsensors = root.getJSONArray(TAG_TEMPSENSORS);

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

                        JSONObject tempsensor = tempsensors.getJSONObject(i);

                        String type = tempsensor.getString(TAG_TYPE);
                        String id = tempsensor.getString(TAG_ID);
                        String crc = tempsensor.getString(TAG_CRC);

                        float temp = (float) tempsensor.getDouble(TAG_TEMP);
                        String tempstr = String.format("%.3f", temp);

                        if (tempstr != null)
                            tempstr = tempstr + " \u2103";

                        tempsensorsArray.add(new Custom_TempSensorsAdapter(type, id, tempstr, crc));
                    }

                    if (tempsensors.length() == 0) {
                        Log.w(LOGTAG, LOGPREFIX + "can't find 1-wire temperature sensors");
                        toast_connection_error(getResources().getString(R.string.error_msg_7));
                    }
                }

            } catch (Exception ex) {
                Log.e(LOGTAG, LOGPREFIX + "received invalid JSON object");
                toast_connection_error(getResources().getString(R.string.error_msg_2));
            }

            setListAdapter(new Custom_TempSensorsArrayAdapter(getApplicationContext(), tempsensorsArray));
        }
    };
}

From source file:com.cleanwiz.applock.service.AppUpdateService.java

public void checkVersion() {
    requestQueue = Volley.newRequestQueue(context);
    String url = "http://www.toolwiz.com/android/checkfiles.php";
    final String oldVersionString = getApplicationVersion();
    Uri.Builder builder = Uri.parse(url).buildUpon();
    builder.appendQueryParameter("uid", AndroidUtil.getUdid(context));
    builder.appendQueryParameter("version", oldVersionString);
    builder.appendQueryParameter("action", "checkfile");
    builder.appendQueryParameter("app", "locklocker");

    jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, builder.toString(), null,
            new Response.Listener<JSONObject>() {

                @Override//from w w  w  .j  a  va 2s  .  c om
                public void onResponse(JSONObject arg0) {
                    // TODO Auto-generated method stub
                    LogUtil.e("colin", "success");
                    if (arg0.has("status")) {
                        try {
                            String status = arg0.getString("status");
                            if (Integer.valueOf(status) == 1) {
                                JSONObject msgJsonObject = arg0.getJSONObject("msg");
                                double version = msgJsonObject.getDouble("version");
                                if (Double.valueOf(oldVersionString) < version) {
                                    // ???
                                    String intro = msgJsonObject.getString("intro");
                                    AlertDialog.Builder alert = new AlertDialog.Builder(context);
                                    alert.setTitle("?").setMessage(intro)
                                            .setPositiveButton("", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                    // ??
                                                }
                                            })
                                            .setNegativeButton("?", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                }
                                            });
                                    alert.create().show();
                                }
                            } else {
                                LogUtil.e("colin", "check update status is error");
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            LogUtil.e("colin", "JSONException" + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError arg0) {
                    // TODO Auto-generated method stub

                }
            });
    requestQueue.add(jsonObjectRequest);
}

From source file:jessmchung.groupon.parsers.DivisionParser.java

@Override
public Division parse(JSONObject json) throws JSONException {
    Division obj = new Division();
    if (json.has("lat"))
        obj.setLat(json.getDouble("lat"));
    if (json.has("lng"))
        obj.setLng(json.getDouble("lng"));
    if (json.has("name"))
        obj.setName(json.getString("name"));
    if (json.has("timezone"))
        obj.setTimezone(json.getString("timezone"));
    if (json.has("id"))
        obj.setId(json.getString("id"));
    if (json.has("timezoneOffsetInSeconds"))
        obj.setTimezoneOffsetInSeconds(json.getInt("timezoneOffsetInSeconds"));
    return obj;/*w  w  w.jav  a2  s  . co  m*/
}

From source file:fr.pasteque.pos.customers.CustomerInfoExt.java

public CustomerInfoExt(JSONObject o) {
    super(null);/*www . j  a v a  2  s  .c  o  m*/
    if (!o.isNull("id")) {
        this.id = o.getString("id");
    }
    if (!o.isNull("number")) {
        this.taxid = o.getString("number");
    }
    if (!o.isNull("dispName")) {
        this.name = o.getString("dispName");
    }
    if (!o.isNull("key")) {
        this.searchkey = o.getString("key");
    }
    if (!o.isNull("custTaxId")) {
        this.taxcustomerid = o.getString("custTaxId");
    }
    if (!o.isNull("discountProfileId")) {
        this.discountProfileId = o.getInt("discountProfileId");
    }
    if (!o.isNull("notes")) {
        this.notes = o.getString("notes");
    }
    this.visible = o.getBoolean("visible");
    if (!o.isNull("card")) {
        this.card = o.getString("card");
    }
    if (!o.isNull("maxDebt")) {
        this.maxdebt = o.getDouble("maxDebt");
    }
    if (!o.isNull("debtDate")) {
        this.curdate = DateUtils.readSecTimestamp(o.getLong("debtDate"));
    }
    if (!o.isNull("currDebt")) {
        this.curdebt = o.getDouble("currDebt");
    }
    this.prepaid = o.getDouble("prepaid");
    if (!o.isNull("firstName")) {
        this.firstname = o.getString("firstName");
    }
    if (!o.isNull("lastName")) {
        this.lastname = o.getString("lastName");
    }
    if (!o.isNull("email")) {
        this.email = o.getString("email");
    }
    if (!o.isNull("phone1")) {
        this.phone = o.getString("phone1");
    }
    if (!o.isNull("phone2")) {
        this.phone2 = o.getString("phone2");
    }
    if (!o.isNull("fax")) {
        this.fax = o.getString("fax");
    }
    if (!o.isNull("addr1")) {
        this.address = o.getString("addr1");
    }
    if (!o.isNull("addr2")) {
        this.address2 = o.getString("addr2");
    }
    if (!o.isNull("zipCode")) {
        this.postal = o.getString("zipCode");
    }
    if (!o.isNull("city")) {
        this.city = o.getString("city");
    }
    if (!o.isNull("region")) {
        this.region = o.getString("region");
    }
    if (!o.isNull("country")) {
        this.country = o.getString("country");
    }
}

From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java

private static Object getCoinValueBTC() {
    Date date = new Date();
    long now = date.getTime();

    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;/*ww  w  .  j  a v a  2 s  .c  om*/
    String currencyCryptsy = CoinDefinition.cryptsyMarketCurrency;
    String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid="
            + CoinDefinition.cryptsyMarketId;

    HttpURLConnection connectionCryptsy = null;
    try {
        // final String currencyCode = currencies[i];
        final URL URLCryptsy = new URL(urlCryptsy);
        connectionCryptsy = (HttpURLConnection) URLCryptsy.openConnection();
        connectionCryptsy.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.connect();

        final StringBuilder contentCryptsy = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024));
            Io.copy(reader, contentCryptsy);
            final JSONObject head = new JSONObject(contentCryptsy.toString());
            JSONObject returnObject = head.getJSONObject("return");
            JSONObject markets = returnObject.getJSONObject("markets");
            JSONObject coinInfo = markets.getJSONObject(CoinDefinition.coinTicker);

            JSONArray recenttrades = coinInfo.getJSONArray("recenttrades");

            double btcTraded = 0.0;
            double coinTraded = 0.0;

            for (int i = 0; i < recenttrades.length(); ++i) {
                JSONObject trade = (JSONObject) recenttrades.get(i);

                btcTraded += trade.getDouble("total");
                coinTraded += trade.getDouble("quantity");

            }

            Double averageTrade = btcTraded / coinTraded;

            //Double lastTrade = GLD.getDouble("lasttradeprice");

            //String euros = String.format("%.7f", averageTrade);
            // Fix things like 3,1250
            //euros = euros.replace(",", ".");
            //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost()));
            if (currencyCryptsy.equalsIgnoreCase("BTC"))
                btcRate = averageTrade;

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException x) {
                    // swallow
                }
            }
        }
        return btcRate;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    } finally {
        if (connectionCryptsy != null)
            connectionCryptsy.disconnect();
    }

    return null;
}

From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java

private static Object getCoinValueBTC_BTER() {
    Date date = new Date();
    long now = date.getTime();

    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;//from w  ww. ja  v  a2  s . c o  m
    String currency = CoinDefinition.cryptsyMarketCurrency;
    String url = "https://bittrex.com/api/v1.1/public/getticker?market=BTC-CANN";

    HttpURLConnection connection = null;
    try {
        // final String currencyCode = currencies[i];
        final URL URL_bter = new URL(url);
        connection = (HttpURLConnection) URL_bter.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connection.connect();

        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            Io.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            String result = head.getString("result");
            if (result.equals("true")) {

                Double averageTrade = head.getDouble("Bid");

                if (currency.equalsIgnoreCase("BTC"))
                    btcRate = averageTrade;
            }

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException x) {
                    // swallow
                }
            }
        }
        return btcRate;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    } finally {
        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:fr.bde_eseo.eseomega.lacommande.model.LacmdElement.java

public LacmdElement(JSONObject obj) throws JSONException {
    super(obj.getString("name"), obj.getString("idstr"), obj.getInt("hasingredients"), 0,
            obj.getDouble("priceuni"), ID_CAT_ELEMENT);
    this.pricemore = obj.getDouble("pricemore");
    this.stock = obj.getInt("stock");
    this.outofmenu = obj.getInt("outofmenu");
    this.idcat = obj.getString("idcat");
}

From source file:com.layer.atlas.messenger.AtlasMessagesScreen.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.uiHandler = new Handler();
    this.app = (MessengerApp) getApplication();

    setContentView(R.layout.atlas_screen_messages);

    boolean convIsNew = getIntent().getBooleanExtra(EXTRA_CONVERSATION_IS_NEW, false);
    String convUri = getIntent().getStringExtra(EXTRA_CONVERSATION_URI);
    if (convUri != null) {
        Uri uri = Uri.parse(convUri);/*ww w.  jav a 2s.  co  m*/
        conv = app.getLayerClient().getConversation(uri);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(convUri.hashCode()); // Clear notifications for this Conversation
    }

    participantsPicker = (AtlasParticipantPicker) findViewById(R.id.atlas_screen_messages_participants_picker);
    participantsPicker.init(new String[] { app.getLayerClient().getAuthenticatedUserId() },
            app.getParticipantProvider());
    if (convIsNew) {
        participantsPicker.setVisibility(View.VISIBLE);
    }

    messageComposer = (AtlasMessageComposer) findViewById(R.id.atlas_screen_messages_message_composer);
    messageComposer.init(app.getLayerClient(), conv);
    messageComposer.setListener(new AtlasMessageComposer.Listener() {
        public boolean beforeSend(Message message) {
            boolean conversationReady = ensureConversationReady();
            if (!conversationReady)
                return false;

            // push
            preparePushMetadata(message);
            return true;
        }

    });

    messageComposer.registerMenuItem("Photo", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            String fileName = "cameraOutput" + System.currentTimeMillis() + ".jpg";
            photoFile = new File(getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES), fileName);
            final Uri outputUri = Uri.fromFile(photoFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            if (debug)
                Log.w(TAG, "onClick() requesting photo to file: " + fileName + ", uri: " + outputUri);
            startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
        }
    });

    messageComposer.registerMenuItem("Image", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            // in onCreate or any event where your want the user to select a file
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_CODE_GALLERY);
        }
    });

    messageComposer.registerMenuItem("Location", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            if (lastKnownLocation == null) {
                Toast.makeText(v.getContext(), "Inserting Location: Location is unknown yet",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            String locationString = "{\"lat\":" + lastKnownLocation.getLatitude() + ", \"lon\":"
                    + lastKnownLocation.getLongitude() + "}";
            MessagePart part = app.getLayerClient().newMessagePart(Atlas.MIME_TYPE_ATLAS_LOCATION,
                    locationString.getBytes());
            Message message = app.getLayerClient().newMessage(Arrays.asList(part));

            preparePushMetadata(message);
            conv.send(message);

            if (debug)
                Log.w(TAG, "onSendLocation() loc:  " + locationString);
        }
    });

    messagesList = (AtlasMessagesList) findViewById(R.id.atlas_screen_messages_messages_list);
    messagesList.init(app.getLayerClient(), app.getParticipantProvider());
    if (USE_QUERY) {
        Query<Message> query = Query.builder(Message.class)
                .predicate(new Predicate(Message.Property.CONVERSATION, Predicate.Operator.EQUAL_TO, conv))
                .sortDescriptor(new SortDescriptor(Message.Property.POSITION, SortDescriptor.Order.ASCENDING))
                .build();
        messagesList.setQuery(query);
    } else {
        messagesList.setConversation(conv);
    }

    messagesList.setItemClickListener(new ItemClickListener() {
        public void onItemClick(Cell cell) {
            if (Atlas.MIME_TYPE_ATLAS_LOCATION.equals(cell.messagePart.getMimeType())) {
                String jsonLonLat = new String(cell.messagePart.getData());
                JSONObject json;
                try {
                    json = new JSONObject(jsonLonLat);
                    double lon = json.getDouble("lon");
                    double lat = json.getDouble("lat");
                    Intent openMapIntent = new Intent(Intent.ACTION_VIEW);
                    String uriString = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f", lat, lon, 18,
                            lat, lon);
                    final Uri geoUri = Uri.parse(uriString);
                    openMapIntent.setData(geoUri);
                    if (openMapIntent.resolveActivity(getPackageManager()) != null) {
                        startActivity(openMapIntent);
                        if (debug)
                            Log.w(TAG, "onItemClick() starting Map: " + uriString);
                    } else {
                        if (debug)
                            Log.w(TAG, "onItemClick() No Activity to start Map: " + geoUri);
                    }
                } catch (JSONException ignored) {
                }
            } else if (cell instanceof ImageCell) {
                Intent intent = new Intent(AtlasMessagesScreen.this.getApplicationContext(),
                        AtlasImageViewScreen.class);
                app.setParam(intent, cell);
                startActivity(intent);
            }
        }
    });

    typingIndicator = (AtlasTypingIndicator) findViewById(R.id.atlas_screen_messages_typing_indicator);
    typingIndicator.init(conv,
            new AtlasTypingIndicator.DefaultTypingIndicatorCallback(app.getParticipantProvider()));

    // location manager for inserting locations:
    this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    prepareActionBar();
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private Boolean parseMetafile(JSONObject metafile) {
    double version;
    boolean forceVersion;
    boolean allowed = false;
    try {/*w  ww  .ja v  a2s .c o  m*/
        version = metafile.getDouble("version");
        forceVersion = metafile.getBoolean("forceVersion");
        JSONObject appDetails = metafile.getJSONObject("app");
        JSONArray assets = metafile.getJSONArray("assets");
        JSONArray devices = metafile.getJSONArray("allowedDevices");

        int nAssets = assets.length();
        String packageName = appDetails.getString("packageName");
        int versionCode = appDetails.getInt("versionCode");
        String apkPath = appDetails.getString("APK");
        boolean offlineSupport = appDetails.getBoolean("offlineSupport");

        if (enableDebug) {
            Log.d(TAG, "Version: " + version + ":" + neoUpdateVersion);
            Log.d(TAG, "Package Name: " + packageName + ":" + packageInfo.packageName);
            Log.d(TAG, "APK Path: " + apkPath);
        }

        // Check if it is being updated using offline storage
        if (!offlineSupport && fromOfflineStorage) {
            Log.e(TAG, "Updating from offline storage is disabled for this app?");
            return false;
        }

        db.clearDevicesList();
        for (int i = 0; i < devices.length(); i++) {
            String device = devices.getString(i);
            if (device.length() > 0 && deviceID.compareToIgnoreCase(device) == 0)
                allowed = true;
            db.insertDevice(device);
            if (enableDebug)
                Log.d(TAG, "Device Allowed: " + device);
        }

        // DeviceID or signature error
        if (!allowed)
            return false;

        apkUpdatePath = null;
        if (version > neoUpdateVersion && forceVersion) {
            Log.e(TAG, "neoUpdate seems to be of older version! Required: " + version + " Current: "
                    + neoUpdateVersion);
            return false;
        }

        if (packageInfo.packageName.compareTo(packageName) != 0) {
            Log.e(TAG, "PackageNames don't seem to match - url for some other app? Provided: " + packageName);
            return false;
        }

        if (packageInfo.versionCode < versionCode) {
            // APK Update Required - Lets first do that
            apkUpdatePath = new NewAsset();
            apkUpdatePath.path = apkPath;
            apkUpdatePath.md5 = appDetails.getString("md5");
            return true;
        }

        // Parse the assets
        for (int i = 0; i < nAssets; i++) {
            JSONObject obj = assets.getJSONObject(i);
            NewAsset asset = new NewAsset();
            asset.path = obj.getString("path");
            asset.md5 = obj.getString("md5");

            // Ignore already downloaded files
            if (db.updateAndGetStatus(asset.path, asset.md5) == neoUpdateDB.UPDATE_STATUS.UPDATE_COMPLETE)
                continue;
            filesToDownload.add(asset);
            if (enableDebug) {
                Log.d(TAG, "Enqueued: " + asset.path + " With MD5: " + asset.md5);
            }
        }
        totalFilesToDownload = filesToDownload.size();
    } catch (Exception e) {
        if (enableDebug)
            e.printStackTrace();
        return false;
    }
    return true;
}

From source file:eu.codeplumbers.cosi.api.tasks.GetPlacesTask.java

@Override
protected List<Place> doInBackground(Void... voids) {
    URL urlO = null;/* ww w .ja v  a2 s  .c  o  m*/
    try {
        urlO = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    String version = "0";
                    if (jsonArray.getJSONObject(i).has("version")) {
                        version = jsonArray.getJSONObject(i).getString("version");
                    }
                    JSONObject placeJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Place place = Place.getByLocation(placeJson.get("description").toString(),
                            placeJson.get("latitude").toString(), placeJson.get("longitude").toString());

                    if (place == null) {
                        place = new Place(placeJson);
                    } else {
                        place.setDeviceId(placeJson.getString("deviceId"));
                        place.setAddress(placeJson.getString("address"));
                        place.setDateAndTime(placeJson.getString("dateAndTime"));
                        place.setLongitude(placeJson.getDouble("longitude"));
                        place.setLatitude(placeJson.getDouble("latitude"));
                        place.setRemoteId(placeJson.getString("_id"));
                    }

                    publishProgress("Saving place : " + place.getAddress());
                    place.save();

                    allPlaces.add(place);
                }
            } else {
                publishProgress("Your Cozy has no places stored.");
                return allPlaces;
            }
        } else {
            errorMessage = "Failed to parse API response";
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    }

    return allPlaces;
}