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:de.dekarlab.moneybuilder.model.parser.JsonBookLoader.java

/**
 * Transactions./*www .j av a2s  .  com*/
 * 
 * @param jsonList
 * @param transactions
 */
protected static void parseTransactions(JSONArray jsonList, List<Transaction> transactions, Book book) {
    boolean transOk;
    if (jsonList != null) {
        for (int i = 0; i < jsonList.length(); i++) {
            transOk = true;
            JSONObject jsonTrans = jsonList.getJSONObject(i);
            Transaction newTrans = new Transaction();
            String from = jsonTrans.getString("from");
            newTrans.setFrom(book.getAccountByName(from));
            if (newTrans.getFrom() == null) {
                Logger.writeToLog("Account is not found: " + from);
                transOk = false;
            }
            String to = jsonTrans.getString("to");
            newTrans.setTo(book.getAccountByName(to));
            if (newTrans.getTo() == null) {
                Logger.writeToLog("Account is not found: " + to);
                transOk = false;
            }

            newTrans.setDescription(jsonTrans.getString("description"));
            newTrans.setValue(jsonTrans.getDouble("value"));
            if (transOk) {
                transactions.add(newTrans);
            }
        }
    }
}

From source file:com.android.dialer.omni.clients.OsmApi.java

/**
 * Fetches and returns Places by sending the provided request
 * @param request the JSON request//from w ww.j av  a 2 s . co  m
 * @return the list of matching places
 * @throws IOException
 * @throws JSONException
 */
private List<Place> getPlaces(String request) throws IOException, JSONException {
    List<Place> places = new ArrayList<Place>();
    // Post and parse request
    JSONObject obj = PlaceUtil.postJsonRequest(mProviderUrl, "data=" + URLEncoder.encode(request));
    JSONArray elements = obj.getJSONArray("elements");

    for (int i = 0; i < elements.length(); i++) {
        JSONObject element = elements.getJSONObject(i);

        Place place = new Place();
        place.setLatitude(element.getDouble("lat"));
        place.setLongitude(element.getDouble("lon"));

        JSONObject tags = element.getJSONObject("tags");
        JSONArray tagNames = tags.names();

        for (int j = 0; j < tagNames.length(); j++) {
            String tagName = tagNames.getString(j);
            String tagValue = tags.getString(tagName);

            // TODO: TAG_PHONE can contain multiple numbers "number1;number2"
            putTag(place, tagName, tagValue);
        }

        places.add(place);
    }
    return places;
}

From source file:com.app.swaedes.swaedes.MapPage.java

public void getJsonMarkers() {

    JsonArrayRequest getMarkers = new JsonArrayRequest(Config.GET_MARKERS, new Response.Listener<JSONArray>() {
        @Override//  w  ww.  ja  va  2 s .  c  om
        public void onResponse(JSONArray response) {
            Log.d("TAG", response.toString());

            try {

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

                    JSONObject marker = (JSONObject) response.get(i);
                    String name = marker.getString("name");
                    Double latitude = marker.getDouble("lat");
                    Double longitude = marker.getDouble("lng");
                    markersList.add(new OverlayItem(name, name, new GeoPoint(latitude, longitude)));
                    Log.d("TAG", marker.toString());
                }

                ItemizedIconOverlay<OverlayItem> mapMarkersOverlay = new ItemizedIconOverlay<>(
                        getApplicationContext(), markersList, null);
                mapView.getOverlays().add(mapMarkersOverlay);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MapPage.this, error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

    //Getting the request queue of the app, add the request to it
    Swaedes swaedes = (Swaedes) getApplication();
    RequestQueue mVolleyRequestQueue = swaedes.getVolleyRequestQueue();
    mVolleyRequestQueue.add(getMarkers);

}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

private void addGeofence(CallbackContext callbackContext, JSONObject config) {
    try {//www .j a v  a  2s  .  c o  m
        String identifier = config.getString("identifier");
        final Bundle event = new Bundle();
        event.putString("name", BackgroundGeolocationService.ACTION_ADD_GEOFENCE);
        event.putBoolean("request", true);
        event.putFloat("radius", (float) config.getLong("radius"));
        event.putDouble("latitude", config.getDouble("latitude"));
        event.putDouble("longitude", config.getDouble("longitude"));
        event.putString("identifier", identifier);

        if (config.has("notifyOnEntry")) {
            event.putBoolean("notifyOnEntry", config.getBoolean("notifyOnEntry"));
        }
        if (config.has("notifyOnExit")) {
            event.putBoolean("notifyOnExit", config.getBoolean("notifyOnExit"));
        }
        if (config.has("notifyOnDwell")) {
            event.putBoolean("notifyOnDwell", config.getBoolean("notifyOnDwell"));
        }
        if (config.has("loiteringDelay")) {
            event.putInt("loiteringDelay", config.getInt("loiteringDelay"));
        }
        addGeofenceCallbacks.put(identifier, callbackContext);

        postEvent(event);

    } catch (JSONException e) {
        e.printStackTrace();
        callbackContext.error(e.getMessage());
    }
}

From source file:edu.cwru.apo.Contract.java

public void onRestRequestComplete(Methods method, JSONObject result) {
    if (method == Methods.getContract) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    String contract = "";
                    contract += "Status: " + result.getString("status") + "\n";
                    contract += "Dues: " + result.getString("dues") + "\n\n";
                    contract += "Chapter Attendance: \n";
                    contract += "Attended: " + result.getDouble("chaptersAttended") + "\n";
                    contract += "Required: " + result.getDouble("chaptersRequired") + "\n\n";
                    contract += "Pledge Attendance: \n";
                    contract += "Attended: " + result.getDouble("pledgeAttended") + "\n";
                    contract += "Required: " + result.getDouble("pledgeRequired") + "\n\n";
                    contract += "Hours:\n";
                    contract += "Hours towards contract: " + result.getDouble("contractHours") + "/"
                            + result.getDouble("contractHoursRequired") + "\n";
                    contract += "Inside Hours: " + result.getDouble("in") + "/" + result.getDouble("inRequired")
                            + "\n";
                    contract += "Outside Hours: " + result.getDouble("out") + "\n";
                    contract += "Total semester Hours: " + result.getDouble("totalHours");
                    text.setText(contract);
                } else if (requestStatus.compareTo("timestamp invalid") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid timestamp.  Please try again.",
                            Toast.LENGTH_LONG);
                    msg.show();//from ww  w. j  a  v  a 2s .  co  m
                } else if (requestStatus.compareTo("HMAC invalid") == 0) {
                    Auth.loggedIn = false;
                    Toast msg = Toast.makeText(getApplicationContext(),
                            "You have been logged out by the server.  Please log in again.", Toast.LENGTH_LONG);
                    msg.show();
                    finish();
                } else if (requestStatus.compareTo("no contract") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "You have not signed a contract.",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid requestStatus",
                            Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:com.mparticle.internal.ConfigManager.java

public boolean shouldTrigger(MPMessage message) {
    JSONArray messageMatches = getTriggerMessageMatches();
    JSONArray triggerHashes = getTriggerMessageHashes();

    //always trigger for PUSH_RECEIVED
    boolean shouldTrigger = message.getMessageType().equals(Constants.MessageType.PUSH_RECEIVED)
            || message.getMessageType().equals(Constants.MessageType.COMMERCE_EVENT);

    if (!shouldTrigger && messageMatches != null && messageMatches.length() > 0) {
        shouldTrigger = true;// w ww.  j a v a  2  s  .  c om
        int i = 0;
        while (shouldTrigger && i < messageMatches.length()) {
            try {
                JSONObject messageMatch = messageMatches.getJSONObject(i);
                Iterator<?> keys = messageMatch.keys();
                while (shouldTrigger && keys.hasNext()) {
                    String key = (String) keys.next();
                    shouldTrigger = message.has(key);
                    if (shouldTrigger) {
                        try {
                            shouldTrigger = messageMatch.getString(key)
                                    .equalsIgnoreCase(message.getString(key));
                        } catch (JSONException stringex) {
                            try {
                                shouldTrigger = message.getBoolean(key) == messageMatch.getBoolean(key);
                            } catch (JSONException boolex) {
                                try {
                                    shouldTrigger = message.getDouble(key) == messageMatch.getDouble(key);
                                } catch (JSONException doubleex) {
                                    shouldTrigger = false;
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {

            }
            i++;
        }
    }
    if (!shouldTrigger && triggerHashes != null) {
        for (int i = 0; i < triggerHashes.length(); i++) {
            try {
                if (triggerHashes.getInt(i) == message.getTypeNameHash()) {
                    shouldTrigger = true;
                    break;
                }
            } catch (JSONException jse) {

            }
        }
    }
    return shouldTrigger;
}

From source file:com.github.koraktor.steamcondenser.community.GameAchievement.java

/**
 * Loads the global unlock percentages of all achievements for the given
 * game//from  w  ww  . ja v a 2s  .c o  m
 *
 * @param appId The unique Steam Application ID of the game (e.g.
 *        <code>440</code> for Team Fortress 2). See
 *        http://developer.valvesoftware.com/wiki/Steam_Application_IDs for
 *        all application IDs
 * @return The symbolic achievement names with the corresponding global
 *         unlock percentages
 * @throws WebApiException if a request to Steam's Web API fails
 */
public static Map<String, Double> getGlobalPercentages(int appId) throws WebApiException {
    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("gameid", appId);

    try {
        JSONObject data = new JSONObject(
                WebApi.getJSON("ISteamUserStats", "GetGlobalAchievementPercentagesForApp", 2, params));

        HashMap<String, Double> percentages = new HashMap<String, Double>();
        JSONArray achievementsData = data.getJSONObject("achievementpercentages").getJSONArray("achievements");
        for (int i = 0; i < achievementsData.length(); i++) {
            JSONObject achievementData = achievementsData.getJSONObject(i);
            percentages.put(achievementData.getString("name"), achievementData.getDouble("percent"));
        }

        return percentages;
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }
}

From source file:com.mohammedsazidalrashid.android.sunshine.ForecastFragment.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.
 *//*from   w ww.j  a  va 2s.  c om*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException {

    // These are the names of the JSON objects that need to be extracted
    final String OWM_LIST = "list";
    final String OWM_WEATHER = "weather";
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";
    final String OWM_DATETIME = "dt";
    final String OWM_DESCRIPTION = "description";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    String[] resultStrs = new String[numDays];
    for (int i = 0; i < weatherArray.length(); i++) {
        // For now, using the format Day - description - hi/low
        String day;
        String description;
        String highAndLow;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        long dateTime = dayForecast.getLong(OWM_DATETIME);
        day = getReadableDateString(dateTime);

        // description is in a child array, which is 1 element long
        description = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0).getString(OWM_DESCRIPTION);

        // Temperatures are in a child object called "temp"
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        double high = temperatureObject.getDouble(OWM_MAX);
        double low = temperatureObject.getDouble(OWM_MIN);
        highAndLow = formatHighLows(high, low);

        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    return resultStrs;
}

From source file:com.delaroystudios.weatherapp.utilities.OpenWeatherJsonUtils.java

/**
 * This method parses JSON from a web response and returns an array of Strings
 * describing the weather over various days from the forecast.
 * <p/>/*from ww w. j  a v a2 s. c  o  m*/
 * Later on, we'll be parsing the JSON into structured data within the
 * getFullWeatherDataFromJson function, leveraging the data we have stored in the JSON. For
 * now, we just convert the JSON into human-readable strings.
 *
 * @param forecastJsonStr JSON response from server
 *
 * @return Array of Strings describing weather data
 *
 * @throws JSONException If JSON data cannot be properly parsed
 */
public static String[] getSimpleWeatherStringsFromJson(Context context, String forecastJsonStr)
        throws JSONException {

    /* Weather information. Each day's forecast info is an element of the "list" array */
    final String OWM_LIST = "list";

    /* All temperatures are children of the "temp" object */
    final String OWM_TEMPERATURE = "temp";

    /* Max temperature for the day */
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";

    final String OWM_MESSAGE_CODE = "cod";

    /* String array to hold each day's weather String */
    String[] parsedWeatherData = null;

    JSONObject forecastJson = new JSONObject(forecastJsonStr);

    /* Is there an error? */
    if (forecastJson.has(OWM_MESSAGE_CODE)) {
        int errorCode = forecastJson.getInt(OWM_MESSAGE_CODE);

        switch (errorCode) {
        case HttpURLConnection.HTTP_OK:
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            /* Location invalid */
            return null;
        default:
            /* Server probably down */
            return null;
        }
    }

    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    parsedWeatherData = new String[weatherArray.length()];

    long localDate = System.currentTimeMillis();
    long utcDate = WeatherDateUtils.getUTCDateFromLocal(localDate);
    long startDay = WeatherDateUtils.normalizeDate(utcDate);

    for (int i = 0; i < weatherArray.length(); i++) {
        String date;
        String highAndLow;

        /* These are the values that will be collected */
        long dateTimeMillis;
        double high;
        double low;
        String description;

        /* Get the JSON object representing the day */
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        /*
         * We ignore all the datetime values embedded in the JSON and assume that
         * the values are returned in-order by day (which is not guaranteed to be correct).
         */
        dateTimeMillis = startDay + WeatherDateUtils.DAY_IN_MILLIS * i;
        date = WeatherDateUtils.getFriendlyDateString(context, dateTimeMillis, false);

        /*
         * 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);

        /*
         * Temperatures are sent by Open Weather Map in a child object called "temp".
         *
         * Editor's Note: Try not to name variables "temp" when working with temperature.
         * It confuses everybody. Temp could easily mean any number of things, including
         * temperature, temporary and is just a bad variable name.
         */
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);
        highAndLow = WeatherUtils.formatHighLows(context, high, low);

        parsedWeatherData[i] = date + " - " + description + " - " + highAndLow;
    }

    return parsedWeatherData;
}

From source file:wassilni.pl.navigationdrawersi.ui.Search.java

public void parseJSON(String s) {
    /*/*from   w  w  w  .ja v a 2 s. c om*/
    * create 3 objects, one for driver, one for schedule and one for car
    * then parse the data into array of 3 arrays, their indices corresponds to the car/driver/schedule arrays
    * then present these data to the user in some order
    *    this solution might not be the best, think of another solution!*/

    String JSON_ARRAY = "result";
    String s_id = "S_ID";
    String sDate = "S_Start_date";
    String eDate = "S_End_date";
    String time = "S_time";
    String mPrice = "monthPrice";
    String dPrice = "dayPrice";
    String BookedSeat = "BookedSeat";
    String pickup = "pickup";
    String dropoff = "dropoff";

    String d_id = "D_ID";
    String FName = "D_F_Name";
    String LName = "D_L_Name";
    String phoneNum = "D_phone";
    String email = "D_Email";
    String company = "company";
    String license = "license";
    String nationality = "nationality";
    String female_companion = "female_companion";
    String id_iqama = "id_iqama";
    String age = "age";
    String rating = "rating";
    String confirmed = "confirmed";

    String Plate_num = "Plate_num";
    String C_company = "C_company";
    String type = "type";
    String model = "model";
    String color = "color";
    String capacity = "capacity";
    String yearOfmanufacture = "yearOfmanufacture";

    showDate();

    /*
    *
    *  this is how to parse values and then assign it to an array
    * public void parseJSON(String s)*/

    try {
        JSONArray auser = null;
        JSONObject j = new JSONObject(s);
        auser = j.getJSONArray("result");
        if (auser.length() > 0) {
            Driver d;
            schedule sched;
            Car car;

            for (int i = 0; i < auser.length(); i++) {
                JSONObject jsonObject = auser.getJSONObject(i);

                /** create schedule  object   **/
                sched = new schedule();
                sched.setS_ID(jsonObject.getInt(s_id));
                sched.setStartDate(jsonObject.getString(sDate));
                sched.setEndDate(jsonObject.getString(eDate));
                sched.setTime(jsonObject.getString(time));
                sched.setPickup(MyApp.getLatlng(jsonObject.getString(pickup)));
                sched.setDropoff(MyApp.getLatlng(jsonObject.getString(dropoff)));
                sched.setBookedSeat(jsonObject.getInt(BookedSeat));
                sched.setMontPrice(jsonObject.getInt(mPrice));
                sched.setDayPrice(jsonObject.getInt(dPrice));

                /** create car object   **/
                car = new Car();
                car.setPlate(jsonObject.getString(Plate_num));
                car.setType(jsonObject.getString(type));
                car.setModel(jsonObject.getString(model));
                car.setColor(jsonObject.getString(color));
                car.setCompany(jsonObject.getString(C_company));
                car.setCapacity(jsonObject.getInt(capacity));
                car.setYearOfManufacture(jsonObject.getInt(yearOfmanufacture));

                /**  create driver object  **/

                System.out.println();
                d = new Driver();
                d.setID(jsonObject.getInt(d_id));
                d.setEmail(jsonObject.getString(email));
                d.setFName(jsonObject.getString(FName));
                d.setLName(jsonObject.getString(LName));
                d.setPhone(jsonObject.getString(phoneNum));
                d.setCompany(jsonObject.getString(company));
                d.setLicense(jsonObject.getString(license));
                d.setNationality(jsonObject.getString(nationality));
                d.setFemaleCompanion(jsonObject.getString(female_companion).charAt(0));
                d.setID_Iqama(jsonObject.getString(id_iqama));
                d.setAge(jsonObject.getString(age));
                d.setRating(jsonObject.getDouble(rating));
                d.setConfirmed(jsonObject.getString(confirmed).charAt(0));
                d.setCar(car);
                // d.getSchedule().add(sched);
                // drivers.add(d);
                searchResult searchR = new searchResult(d, sched);
                searchResults.add(searchR);
                /* int D_id =jsonObject.getInt(d_id);
                 boolean flag = true;
                 for(int a=0;a<drivers.size();a++){
                     if(drivers.get(a).getID()==D_id){
                        
                         drivers.get(a).setCar(car);
                         drivers.get(a).getSchedule().add(sched);
                         flag=false;
                         break;
                        
                     }
                        
                 }*/

                //schedules.add(sched);
                /*  if(flag) {
                      System.out.println();
                      d = new Driver();
                      d.setID(jsonObject.getInt(d_id));
                      d.setEmail(jsonObject.getString(email));
                      d.setFName(jsonObject.getString(FName));
                      d.setLName(jsonObject.getString(LName));
                      d.setPhone(jsonObject.getString(phoneNum));
                      d.setCompany(jsonObject.getString(company));
                      d.setLicense(jsonObject.getString(license));
                      d.setNationality(jsonObject.getString(nationality));
                      d.setFemaleCompanion(jsonObject.getString(female_companion).charAt(0));
                      d.setID_Iqama(jsonObject.getString(id_iqama));
                      d.setAge(jsonObject.getString(age));
                      d.setRating(jsonObject.getDouble(rating));
                      d.setConfirmed(jsonObject.getString(confirmed).charAt(0));
                      d.setCar(car);
                      d.getSchedule().add(sched);
                      drivers.add(d);
                        
                  }*/

            } //end for auser.length
        } // if JSON EMPTY
        else
            Toast.makeText(getApplicationContext(), "    ?",
                    Toast.LENGTH_SHORT).show();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // for (int i=0 ; i< drivers.size();i++)
    //  System.out.println(drivers.get(i).toString()+"\t"+schedules.get(i).getS_ID());
}