Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

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

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:views.online.Panel_RejoindrePartieMulti.java

/**
 * Permet de mettre a jour la liste des serveurs avec une rponse JSON
 * /*ww  w.  ja v  a2s.c o  m*/
 * @param resultatJSON le rsultat du serveur d'enregistrement
 */
private void mettreAJourListeDepuisJSON(String resultatJSON) {
    try {
        // Analyse de la rponse du serveur d'enregistrement
        JSONObject jsonResultat = new JSONObject(resultatJSON);

        // on vide la liste des serveurs
        serveurs.clear();

        if (jsonResultat.getInt("status") == CodeRegisterment.OK) {
            // slection des serveurs de jeu
            JSONArray jsonArray = jsonResultat.getJSONArray("parties");

            // ajout des serveurs de jeu
            int i = 0;
            for (; i < jsonArray.length(); i++) {
                JSONObject serveur = jsonArray.getJSONObject(i);

                ajouterServeur(serveur.getString("nomPartie"), serveur.getString("adresseIp"),
                        serveur.getInt("numeroPort"), serveur.getString("mode"),
                        serveur.getString("nomTerrain"), serveur.getInt("capacite"),
                        serveur.getInt("placesRestantes"));

            }

            if (i > 0)
                tbServeurs.setRowSelectionInterval(0, 0);

            lblEtat.setForeground(LookInterface.COULEUR_SUCCES);
            lblEtat.setText(Language.getTexte(Language.ID_TXT_CON_SRV_CENTRAL_ETABLIE));
        } else {
            lblEtat.setForeground(LookInterface.COULEUR_SUCCES);
            lblEtat.setText(Language.getTexte(Language.ID_TXT_CON_SRV_CENTRAL_ETABLIE) + " ["
                    + Language.getTexte(Language.ID_TXT_AUCUN_SRV_DISPONIBLE) + "]");
        }
    } catch (JSONException e1) {
        lblEtat.setForeground(LookInterface.COULEUR_ERREUR);
        lblEtat.setText("Format de rponse du serveur incorrect!");
    }
}

From source file:com.roiland.crm.sm.core.service.impl.ProjectAPIImpl.java

/**
 * @see com.roiland.crm.core.service.ProjectAPI#getProjectList()
 *//*w  ww .j  av  a 2s .  com*/
@Override
public List<Project> getProjectList(String searchWord, String searchColumns, String expired, Integer startNum,
        Integer rowCount, Project.AdvancedSearch advancedSearch) throws ResponseException {
    // ?
    ReleasableList<Project> projectList = null;
    try {
        JSONObject params = new JSONObject();
        params.put("searchWord", searchWord);
        params.put("searchColumns", searchColumns);
        params.put("startNum", startNum);
        params.put("rowCount", rowCount);
        params.put("expired", expired);
        params.put("searchType", "0");

        //??
        if (advancedSearch != null) {
            params.put("brand", advancedSearch.getBrand());
            params.put("intentAuto", advancedSearch.getModel());
            params.put("flowid", advancedSearch.getFollowStatus());
            params.put("owner", advancedSearch.getOwner());
            params.put("startDate", advancedSearch.getStartDate());
            params.put("closeDate", advancedSearch.getEndDate());
            params.put("orderBy", advancedSearch.getOrderBy());
        }

        // ?Key
        @SuppressWarnings("unused")
        String key = getKey(URLContact.METHOD_GET_PROJECT_LIST, params);
        RLHttpResponse response = getHttpClient()
                .executePostJSON(getURLAddress(URLContact.METHOD_GET_PROJECT_LIST), params, null);

        if (response.isSuccess()) {
            projectList = new ArrayReleasableList<Project>();
            JSONObject jsonBean = new JSONObject(getSimpleString(response));
            JSONArray project = jsonBean.getJSONArray("result");

            for (int i = 0; i < project.length(); i++) {
                try {
                    JSONObject json = project.getJSONObject(i);
                    Project result = new Project();
                    Customer cust = new Customer();
                    result.setProjectID(json.getString("projectID")); //project IDProject
                    cust.setProjectID(json.getString("projectID"));
                    cust.setCustName(json.getString("custName"));
                    cust.setCustMobile(json.getString("custMobile"));
                    cust.setCustOtherPhone(json.getString("custOtherPhone"));
                    cust.setHasUnexePlan(json.getString("hasUnexePlan"));
                    cust.setCustomerID(json.getString("customerID"));
                    cust.setCustFrom(json.getString("custFrom"));
                    cust.setCustFromCode(json.getString("custFromCode"));
                    cust.setCustType(json.getString("custType"));
                    cust.setCustTypeCode(json.getString("custTypeCode"));
                    cust.setCustComment(json.getString("custComment"));
                    cust.setIdNumber(json.getString("idNumber"));

                    PurchaseCarIntention purchaseCarIntention = new PurchaseCarIntention();
                    purchaseCarIntention.setBrandCode(json.getString("brandCode"));
                    purchaseCarIntention.setBrand(json.getString("brand"));
                    purchaseCarIntention.setModelCode(json.getString("modelCode"));
                    purchaseCarIntention.setModel(json.getString("model"));
                    purchaseCarIntention.setFlowStatus(json.getString("flowStatus"));
                    purchaseCarIntention.setInsideColorCheck(
                            Boolean.parseBoolean(String.valueOf(json.getString("insideColorCheck"))));
                    purchaseCarIntention.setPreorderDate(parsingLong(json.getString("preorderDate")));
                    purchaseCarIntention.setCreateDate(parsingLong(json.getString("createDate")));
                    purchaseCarIntention.setProjectComment(json.getString("projectComment"));
                    purchaseCarIntention.setOutsideColorCode(json.getString("outsideColorCode"));
                    purchaseCarIntention.setOutsideColor(json.getString("outsideColor"));
                    purchaseCarIntention.setInsideColor(json.getString("insideColor"));
                    purchaseCarIntention.setInsideColorCode(json.getString("insideColorCode"));
                    purchaseCarIntention.setCarConfiguration(json.getString("carConfiguration"));
                    purchaseCarIntention.setCarConfigurationCode(json.getString("carConfigurationCode"));
                    purchaseCarIntention.setEmployeeName(json.getString("employeeName"));
                    purchaseCarIntention.setAbandonFlag(json.getString("abandonFlag"));

                    result.setCustomer(cust);
                    result.setPurchaseCarIntention(purchaseCarIntention);
                    projectList.add(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return projectList;
        }
        throw new ResponseException();
    } catch (IOException e) {
        Log.e(tag, "Connection network error.", e);
        throw new ResponseException(e);
    } catch (JSONException e) {
        Log.e(tag, "Parsing data error.", e);
        throw new ResponseException(e);
    } catch (Exception e) {
        throw new ResponseException(e);
    }
}

From source file:com.roiland.crm.sm.core.service.impl.ProjectAPIImpl.java

/**
 * @see com.roiland.crm.core.service.ProjectAPI#getCustomerProjectList(java.lang.String, java.lang.String)
 *//*w  w w .  j  av a 2  s .c  o  m*/
@SuppressWarnings("unchecked")
@Override
public List<Project> getCustomerProjectList(String userID, String customerID) throws ResponseException {
    // ?
    ReleasableList<Project> projectList = null;
    try {
        if (userID == null) {
            throw new ResponseException("userID is null.");
        }
        JSONObject params = new JSONObject();
        params.put("userID", userID);
        params.put("customerID", customerID);

        // ?Key
        String key = getKey(URLContact.METHOD_GET_CUSTOMER_PROJECT_LIST, params);

        RLHttpResponse response = getHttpClient()
                .executePostJSON(getURLAddress(URLContact.METHOD_GET_CUSTOMER_PROJECT_LIST), params, null);

        if (response.isSuccess()) {
            projectList = new ArrayReleasableList<Project>();
            JSONObject jsonBean = new JSONObject(getSimpleString(response));
            JSONArray project = jsonBean.getJSONArray("result");

            for (int i = 0; i < project.length(); i++) {
                JSONObject json = project.getJSONObject(i);
                Project result = new Project();
                Customer cust = new Customer();
                result.setProjectID("projectID");
                cust.setProjectID(json.getString("projectID"));
                cust.setCustName(json.getString("custName"));
                cust.setCustMobile(json.getString("custMobile"));
                cust.setCustOtherPhone(json.getString("custOtherPhone"));
                cust.setHasUnexePlan(json.getString("hasUnexePlan"));
                cust.setCustomerID(json.getString("customerID"));
                cust.setCustFrom(json.getString("custFrom"));
                cust.setCustFromCode(json.getString("custFromCode"));
                cust.setCustType(json.getString("custType"));
                cust.setCustTypeCode(json.getString("custTypeCode"));
                cust.setCustComment(json.getString("custComment"));
                cust.setIdNumber(json.getString("idNumber"));

                PurchaseCarIntention purchaseCarIntention = new PurchaseCarIntention();
                purchaseCarIntention.setBrandCode(json.getString("brandCode"));
                purchaseCarIntention.setBrand(parsingString(json.get("brand")));
                purchaseCarIntention.setModelCode(json.getString("modelCode"));
                purchaseCarIntention.setModel(parsingString(json.get("model")));
                purchaseCarIntention.setFlowStatus(parsingString(json.get("flowStatus")));
                purchaseCarIntention.setFlowStatusCode("flowStatusCode");
                purchaseCarIntention.setInsideColorCheck(
                        Boolean.parseBoolean(String.valueOf(json.getString("insideColorCheck"))));

                purchaseCarIntention.setPreorderDate(json.getLong("preorderDate"));
                purchaseCarIntention.setProjectComment(json.getString("projectComment"));
                purchaseCarIntention.setOutsideColorCode(json.getString("outsideColorCode"));
                purchaseCarIntention.setOutsideColor(json.getString("outsideColor"));
                purchaseCarIntention.setInsideColor(json.getString("insideColor"));
                purchaseCarIntention.setInsideColorCode(json.getString("insideColorCode"));
                purchaseCarIntention.setCarConfiguration(json.getString("carConfiguration"));
                purchaseCarIntention.setCarConfigurationCode(json.getString("carConfigurationCode"));

                result.setCustomer(cust);
                result.setPurchaseCarIntention(purchaseCarIntention);
                projectList.add(result);
            }

            return projectList;
        }
        throw new ResponseException();
    } catch (IOException e) {
        Log.e(tag, "Connection network error.", e);
        throw new ResponseException(e);
    } catch (JSONException e) {
        Log.e(tag, "Parsing data error.", e);
        throw new ResponseException(e);
    } catch (Exception e) {
        throw new ResponseException(e);
    }
}

From source file:com.roiland.crm.sm.core.service.impl.ProjectAPIImpl.java

@Override
public List<Project> getTodayProjectList(String searchText, String searchColumns, int startNum, int rowCount,
        String status) throws ResponseException {
    ReleasableList<Project> projectList = null;
    try {/*  w  w  w. j a v  a 2  s. c  o  m*/
        JSONObject params = new JSONObject();
        params.put("searchWord", searchText);
        params.put("searchColumns", searchColumns);
        params.put("startNum", startNum);
        params.put("rowCount", rowCount);
        params.put("status", status);
        params.put("searchType", "0");

        RLHttpResponse response = getHttpClient()
                .executePostJSON(getURLAddress(URLContact.METHOD_GET_TODAY_PROJECT_LIST), params, null);
        if (response.isSuccess()) {
            projectList = new ArrayReleasableList<Project>();
            JSONObject jsonBean = new JSONObject(getSimpleString(response));
            JSONArray array = jsonBean.getJSONArray("result");
            for (int i = 0; i < array.length(); i++) {
                JSONObject json = array.getJSONObject(i);
                Project result = new Project();
                Customer cust = new Customer();
                result.setProjectID(json.getString("projectID")); //project IDProject
                cust.setProjectID(json.getString("projectID"));
                cust.setCustName(json.getString("custName"));
                cust.setCustMobile(json.getString("custMobile"));
                cust.setCustOtherPhone(json.getString("custOtherPhone"));
                cust.setHasUnexePlan(json.getString("hasUnexePlan"));
                cust.setCustomerID(json.getString("customerID"));
                cust.setCustFrom(json.getString("custFrom"));
                cust.setCustFromCode(json.getString("custFromCode"));
                cust.setCustType(json.getString("custType"));
                cust.setCustTypeCode(json.getString("custTypeCode"));
                cust.setCustComment(json.getString("custComment"));
                cust.setIdNumber(json.getString("idNumber"));

                PurchaseCarIntention purchaseCarIntention = new PurchaseCarIntention();
                purchaseCarIntention.setBrandCode(json.getString("brandCode"));
                purchaseCarIntention.setBrand(json.getString("brand"));
                purchaseCarIntention.setModelCode(json.getString("modelCode"));
                purchaseCarIntention.setModel(json.getString("model"));
                purchaseCarIntention.setFlowStatus(json.getString("flowStatus"));
                purchaseCarIntention.setInsideColorCheck(
                        Boolean.parseBoolean(String.valueOf(json.getString("insideColorCheck"))));
                purchaseCarIntention.setPreorderDate(json.getLong("preorderDate"));
                purchaseCarIntention.setProjectComment(json.getString("projectComment"));
                purchaseCarIntention.setOutsideColorCode(json.getString("outsideColorCode"));
                purchaseCarIntention.setOutsideColor(json.getString("outsideColor"));
                purchaseCarIntention.setInsideColor(json.getString("insideColor"));
                purchaseCarIntention.setInsideColorCode(json.getString("insideColorCode"));
                purchaseCarIntention.setCarConfiguration(json.getString("carConfiguration"));
                purchaseCarIntention.setCarConfigurationCode(json.getString("carConfigurationCode"));
                purchaseCarIntention.setEmployeeName(json.getString("employeeName"));
                purchaseCarIntention.setCreateDate(parsingLong(json.getString("createDate")));

                result.setCustomer(cust);
                result.setPurchaseCarIntention(purchaseCarIntention);
                projectList.add(result);
            }
        }

    } catch (IOException e) {
        throw new ResponseException(e);
    } catch (JSONException e) {
        throw new ResponseException(e);
    }
    return projectList;
}

From source file:com.roiland.crm.sm.core.service.impl.ProjectAPIImpl.java

@Override
public List<Project> getExpiredProjectList(String searchText, String searchColumns, int startNum, int rowCount)
        throws ResponseException {
    ReleasableList<Project> projectList = null;
    try {//from  ww w. ja  va  2s .c o  m
        JSONObject params = new JSONObject();
        params.put("searchWord", searchText);
        params.put("searchColumns", searchColumns);
        params.put("startNum", startNum);
        params.put("rowCount", rowCount);
        params.put("searchType", "0");

        RLHttpResponse response = getHttpClient()
                .executePostJSON(getURLAddress(URLContact.METHOD_GET_EXPIRED_PROJECT_LIST), params, null);
        if (response.isSuccess()) {
            projectList = new ArrayReleasableList<Project>();
            JSONObject jsonBean = new JSONObject(getSimpleString(response));
            JSONArray array = jsonBean.getJSONArray("result");
            for (int i = 0; i < array.length(); i++) {
                JSONObject json = array.getJSONObject(i);
                Project result = new Project();
                Customer cust = new Customer();
                result.setProjectID(json.getString("projectID")); //project IDProject
                cust.setProjectID(json.getString("projectID"));
                cust.setCustName(json.getString("custName"));
                cust.setCustMobile(json.getString("custMobile"));
                cust.setCustOtherPhone(json.getString("custOtherPhone"));
                cust.setHasUnexePlan(json.getString("hasUnexePlan"));
                cust.setCustomerID(json.getString("customerID"));
                cust.setCustFrom(json.getString("custFrom"));
                cust.setCustFromCode(json.getString("custFromCode"));
                cust.setCustType(json.getString("custType"));
                cust.setCustTypeCode(json.getString("custTypeCode"));
                cust.setCustComment(json.getString("custComment"));
                cust.setIdNumber(json.getString("idNumber"));

                PurchaseCarIntention purchaseCarIntention = new PurchaseCarIntention();
                purchaseCarIntention.setBrandCode(json.getString("brandCode"));
                purchaseCarIntention.setBrand(json.getString("brand"));
                purchaseCarIntention.setModelCode(json.getString("modelCode"));
                purchaseCarIntention.setModel(json.getString("model"));
                purchaseCarIntention.setFlowStatus(json.getString("flowStatus"));
                purchaseCarIntention.setInsideColorCheck(
                        Boolean.parseBoolean(String.valueOf(json.getString("insideColorCheck"))));
                purchaseCarIntention.setPreorderDate(json.getLong("preorderDate"));
                purchaseCarIntention.setProjectComment(json.getString("projectComment"));
                purchaseCarIntention.setOutsideColorCode(json.getString("outsideColorCode"));
                purchaseCarIntention.setOutsideColor(json.getString("outsideColor"));
                purchaseCarIntention.setInsideColor(json.getString("insideColor"));
                purchaseCarIntention.setInsideColorCode(json.getString("insideColorCode"));
                purchaseCarIntention.setCarConfiguration(json.getString("carConfiguration"));
                purchaseCarIntention.setCarConfigurationCode(json.getString("carConfigurationCode"));
                purchaseCarIntention.setEmployeeName(json.getString("employeeName"));

                result.setCustomer(cust);
                result.setPurchaseCarIntention(purchaseCarIntention);
                projectList.add(result);
            }
        }

    } catch (IOException e) {
        throw new ResponseException(e);
    } catch (JSONException e) {
        throw new ResponseException(e);
    }
    return projectList;
}

From source file:com.roiland.crm.sm.core.service.impl.ProjectAPIImpl.java

/** 
 * @see com.roiland.crm.sm.core.service.ProjectAPI#searchSalesOppoFunncelList(long, long)
 *//*w  w w  . j ava 2  s  .  co  m*/
@Override
public List<Project> searchSalesOppoFunncelList(long startDate, long endDate, int startNum, int rowCount)
        throws ResponseException {
    ReleasableList<Project> projectList = null;
    try {
        JSONObject params = new JSONObject();
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("startNum", startNum);
        params.put("rowCount", rowCount);

        RLHttpResponse response = getHttpClient()
                .executePostJSON(getURLAddress(URLContact.METHOD_GET_SEARCH_PROJECT_FUNNEL), params, null);
        if (response.isSuccess()) {
            projectList = new ArrayReleasableList<Project>();
            JSONObject jsonBean = new JSONObject(getSimpleString(response));

            JSONArray array = jsonBean.getJSONArray("list");
            if (array != null) {
                for (int i = 0; i < array.length(); i++) {
                    JSONObject json = array.getJSONObject(i);
                    Project result = new Project();
                    Customer cust = new Customer();
                    result.setProjectID(json.getString("projectID")); //project IDProject
                    cust.setProjectID(json.getString("projectID"));
                    cust.setCustName(parsingString(json.get("custName"))); //??

                    PurchaseCarIntention purchaseCarIntention = new PurchaseCarIntention();
                    purchaseCarIntention.setBrand(parsingString(json.get("brand"))); //?
                    purchaseCarIntention.setModel(parsingString(json.get("model"))); //
                    purchaseCarIntention.setFlowStatus(parsingString(json.get("flowStatus"))); //??
                    purchaseCarIntention.setPreorderDate(parsingLong(json.getString("provideDate"))); //
                    purchaseCarIntention.setProjectComment(parsingString(json.get("moment"))); //
                    purchaseCarIntention.setOutsideColor(parsingString(json.get("outsideColor"))); //
                    purchaseCarIntention.setInsideColor(parsingString(json.get("insideColor"))); //
                    purchaseCarIntention.setAbandonFlag(parsingString(json.get("abandonFlag"))); //??
                    purchaseCarIntention.setPreorderCount(parsingString(json.get("revenue"))); //?
                    purchaseCarIntention.setDealPossibility(parsingString(json.get("win"))); //??
                    purchaseCarIntention.setDealPriceInterval(parsingString(json.get("expect"))); //
                    purchaseCarIntention.setEmployeeName(parsingString(json.get("saleMan"))); //

                    result.setCustomer(cust);
                    result.setPurchaseCarIntention(purchaseCarIntention);
                    projectList.add(result);
                }
            }
        }

    } catch (IOException e) {
        throw new ResponseException(e);
    } catch (JSONException e) {
        throw new ResponseException(e);
    }
    return projectList;
}

From source file:com.mifos.mifosxdroid.dialogfragments.loanaccountdisbursement.LoanAccountDisbursement.java

@Override
public void showLoanTemplate(ResponseBody result) {

    final ArrayList<PaymentTypeOptions> paymentOption = new ArrayList<PaymentTypeOptions>();
    final ArrayList<String> paymentNames = new ArrayList<String>();
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    String line;// w ww .j a va  2s  .  c om
    try {
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("paymentTypeOptions")) {
            JSONArray paymentOptions = obj.getJSONArray("paymentTypeOptions");
            for (int i = 0; i < paymentOptions.length(); i++) {
                JSONObject paymentObject = paymentOptions.getJSONObject(i);
                PaymentTypeOptions payment = new PaymentTypeOptions();
                payment.setId(paymentObject.optInt("id"));
                payment.setName(paymentObject.optString("name"));
                paymentOption.add(payment);
                paymentNames.add(paymentObject.optString("name"));
                paymentNameIdHashMap.put(payment.getName(), payment.getId());
            }
        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    ArrayAdapter<String> paymentAdapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_spinner_item, paymentNames);
    paymentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp_payment_type.setAdapter(paymentAdapter);
    sp_payment_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            paymentTypeId = paymentNameIdHashMap.get(paymentNames.get(i));
            Log.d("paymentId " + paymentNames.get(i), String.valueOf(paymentTypeId));
            if (paymentTypeId != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_payment), Toast.LENGTH_SHORT)
                        .show();

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

From source file:xanthanov.droid.funrun.PlaceSearcher.java

private List<GooglePlace> parseJsonResult(BufferedReader in) throws GmapException, IOException, JSONException {

    String jsonString = new String();
    String aLine = null;//www  .  j  av a2s  .c  o m
    List<GooglePlace> foundPlaces = new ArrayList<GooglePlace>();
    String status = null;
    JSONObject jObj = null;

    while ((aLine = in.readLine()) != null) {
        //   System.out.println(aLine);
        jsonString += aLine;
    }

    jObj = (JSONObject) new JSONTokener(jsonString).nextValue();
    status = jObj.getString("status");
    JSONArray results = jObj.getJSONArray("results");

    if (status.equals("ZERO_RESULTS")) {
        return foundPlaces; //Return empty array if no results 
    } else if (!status.equals("OK")) {
        throw new GmapException("Google Maps returned an error code:\n" + status);
    }

    for (int i = 0; i < results.length(); i++) {
        foundPlaces.add(parseGmapResult(results.getJSONObject(i)));
    }

    return foundPlaces;
}

From source file:com.kwang.sunshine.FetchWeatherTask.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.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.//from  w  ww  .j  a v  a2 s  .c  o  m
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting)
        throws JSONException {

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";
    final String OWM_COORD_LAT = "lat";
    final String OWM_COORD_LONG = "lon";

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

    final String OWM_DATETIME = "dt";
    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

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

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

    JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
    String cityName = cityJson.getString(OWM_CITY_NAME);
    JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD);
    double cityLatitude = coordJSON.getLong(OWM_COORD_LAT);
    double cityLongitude = coordJSON.getLong(OWM_COORD_LONG);

    Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude);

    // Insert the location into the database.
    long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

    // Get and insert the new weather information into the database
    Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

    String[] resultStrs = new String[numDays];

    for (int i = 0; i < weatherArray.length(); i++) {
        // These are the values that will be collected.

        long dateTime;
        double pressure;
        int humidity;
        double windSpeed;
        double windDirection;

        double high;
        double low;

        String description;
        int weatherId;

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

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        dateTime = dayForecast.getLong(OWM_DATETIME);

        pressure = dayForecast.getDouble(OWM_PRESSURE);
        humidity = dayForecast.getInt(OWM_HUMIDITY);
        windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
        windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

        // 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);
        weatherId = weatherObject.getInt(OWM_WEATHER_ID);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);

        ContentValues weatherValues = new ContentValues();

        weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID);
        weatherValues.put(WeatherEntry.COLUMN_DATETEXT,
                WeatherContract.getDbDateString(new Date(dateTime * 1000L)));
        weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
        weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
        weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
        weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
        weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
        weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
        weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
        weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

        cVVector.add(weatherValues);

        String highAndLow = formatHighLows(high, low);
        String day = getReadableDateString(dateTime);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    if (cVVector.size() > 0) {
        ContentValues[] cvArray = new ContentValues[cVVector.size()];
        cVVector.toArray(cvArray);
        int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data");
        // Use a DEBUG variable to gate whether or not you do this, so you can easily
        // turn it on and off, and so that it's easy to see what you can rip out if
        // you ever want to remove it.
        if (DEBUG) {
            Cursor weatherCursor = mContext.getContentResolver().query(WeatherEntry.CONTENT_URI, null, null,
                    null, null);

            if (weatherCursor.moveToFirst()) {
                ContentValues resultValues = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(weatherCursor, resultValues);
                Log.v(LOG_TAG, "Query succeeded! **********");
                for (String key : resultValues.keySet()) {
                    Log.v(LOG_TAG, key + ": " + resultValues.getAsString(key));
                }
            } else {
                Log.v(LOG_TAG, "Query failed! :( **********");
            }
        }
    }

    return resultStrs;
}

From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenDevi.java

@Override
public void run() {
    try {//www .  ja va2  s. c o m
        //String urlString = "http://devi.trafikanten.no/devirest.svc/json/linenames/";
        String urlString = "http://devi.trafikanten.no/devirest.svc/json/lineids/";
        if (lines.length() > 0) {
            urlString = urlString + URLEncoder.encode(lines, "UTF-8");
        } else {
            urlString = urlString + "null";
        }
        urlString = urlString + "/stopids/" + stationId + "/";
        urlString = urlString + "from/" + dateFormater.format(System.currentTimeMillis()) + "/to/2030-12-31";
        Log.i(TAG, "Loading devi data : " + urlString);

        final InputStream stream = HelperFunctions.executeHttpRequest(context, new HttpGet(urlString),
                false).stream;

        /*
         * Parse json
         */
        final JSONArray jsonArray = new JSONArray(HelperFunctions.InputStreamToString(stream));
        final int arraySize = jsonArray.length();
        for (int i = 0; i < arraySize; i++) {
            final JSONObject json = jsonArray.getJSONObject(i);
            DeviData deviData = new DeviData();

            {
                /*
                 * Grab validFrom and check if we should show it or not.
                 */
                deviData.validFrom = HelperFunctions.jsonToDate(json.getString("validFrom"));
                final long dateDiffHours = (deviData.validFrom - Calendar.getInstance().getTimeInMillis())
                        / HelperFunctions.HOUR;
                if (dateDiffHours > 3) {
                    /*
                     * This data starts more than 3 hours into the future, hide it.
                     */
                    continue;
                }
            }
            {
                /*
                 * Grab published, and see if this should be visible yet.
                 */
                final long publishDate = HelperFunctions.jsonToDate(json.getString("published"));
                if (System.currentTimeMillis() < publishDate) {
                    continue;
                }
            }
            {
                /*
                 * Check validto, and see if this should be visible yet.
                 */
                final long validToDate = HelperFunctions.jsonToDate(json.getString("validTo"));
                if (System.currentTimeMillis() > validToDate) {
                    continue;
                }
            }

            /*
             * Grab the easy data
             */
            deviData.title = json.getString("header");
            deviData.description = json.getString("lead");
            deviData.body = json.getString("body");
            deviData.validTo = HelperFunctions.jsonToDate(json.getString("validTo"));
            deviData.important = json.getBoolean("important");
            deviData.id = json.getInt("id");

            {
                /*
                 * Grab lines array
                 */
                final JSONArray jsonLines = json.getJSONArray("lines");
                final int jsonLinesSize = jsonLines.length();
                for (int j = 0; j < jsonLinesSize; j++) {
                    deviData.lines.add(jsonLines.getJSONObject(j).getInt("lineID"));
                }
            }

            {
                /*
                 * Grab stops array
                 */
                final JSONArray jsonLines = json.getJSONArray("stops");
                final int jsonLinesSize = jsonLines.length();
                for (int j = 0; j < jsonLinesSize; j++) {
                    deviData.stops.add(jsonLines.getJSONObject(j).getInt("stopID"));
                }
            }

            ThreadHandlePostData(deviData);
        }

    } catch (Exception e) {
        if (e.getClass() == InterruptedException.class) {
            ThreadHandlePostExecute(null);
            return;
        }
        ThreadHandlePostExecute(e);
        return;
    }
    ThreadHandlePostExecute(null);
}