Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

In this page you can find the example usage for org.json JSONArray getJSONObject.

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:project.getphrase.PhraseService.java

public ArrayList<Phrase> getPhraseS(int bmilvl, int change, int w1, int w2, int w3)
        throws MalformedURLException, IOException, JSONException {

    String url = "";
    url += Settings.BASE_PROTOCOL + Settings.PH_BASE_URL + Settings.PH_BASE_PORT + Settings.PH_BASE_PATH;
    url += "?" + Settings.PH_PARAM_BMI_LEVEL + "=" + bmilvl;
    url += "&" + Settings.PH_PARAM_CHANGE + "=" + change;
    url += "&" + Settings.PH_PARAM_WEATHER_TYPE_1 + "=" + w1;
    url += "&" + Settings.PH_PARAM_WEATHER_TYPE_2 + "=" + w2;
    url += "&" + Settings.PH_PARAM_WEATHER_TYPE_3 + "=" + w3;

    System.out.println("URL: " + url);

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod(REQ_TYPE);//from w  ww. ja  v  a 2  s  .c  o  m

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    ArrayList<Phrase> retPhs = new ArrayList<Phrase>();
    JSONArray phs = new JSONArray(response.toString());
    for (int i = 0; i < phs.length(); i++) {
        JSONObject o = phs.getJSONObject(i);
        Phrase p = new Phrase();
        p.setIdphrase(o.getInt(Settings.PH_JSON_ID_PHRASE));
        p.setPhrase(o.getString(Settings.PH_JSON_PHRASE));
        p.setWeathertype(o.getInt(Settings.PH_JSON_WEATHER_TYPE));
        p.setBmirange(o.getInt(Settings.PH_JSON_BMIRANGE));
        p.setChange(o.getInt(Settings.PH_JSON_CHANGE));
        p.setActivity(o.getString(Settings.PH_JSON_ACTIVITY));
        retPhs.add(p);
    }
    return retPhs;
}

From source file:com.liferay.mobile.android.v7.classname.ClassNameService.java

public JSONObject fetchClassName(String value) throws Exception {
    JSONObject _command = new JSONObject();

    try {/*  w  ww  .j a va2s .  com*/
        JSONObject _params = new JSONObject();

        _params.put("value", checkNull(value));

        _command.put("/classname/fetch-class-name", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

private void inflateAmortizationSpinner(ResponseBody result) {

    final List<AmortizationType> amortizationType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> amortizationTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {// w  w  w.  java2s .  c  o  m
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("amortizationTypeOptions")) {
            JSONArray amortizationTypes = obj.getJSONArray("amortizationTypeOptions");
            for (int i = 0; i < amortizationTypes.length(); i++) {
                JSONObject amortizationTypeObject = amortizationTypes.getJSONObject(i);
                AmortizationType amortization = new AmortizationType();
                amortization.setId(amortizationTypeObject.optInt("id"));
                amortization.setValue(amortizationTypeObject.optString("value"));
                amortizationType.add(amortization);
                amortizationTypeNames.add(amortizationTypeObject.optString("value"));
                amortizationTypeIdHashMap.put(amortization.getValue(), amortization.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> amortizationTypeAdapter = new ArrayAdapter<>(getActivity(),
            layout.simple_spinner_item, amortizationTypeNames);
    amortizationTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
    sp_amortization.setAdapter(amortizationTypeAdapter);
    sp_amortization.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            amortizationTypeId = amortizationTypeIdHashMap.get(amortizationTypeNames.get(i));
            Log.d("ammortization" + amortizationTypeNames.get(i), String.valueOf(amortizationTypeId));
            if (amortizationTypeId != -1) {

            } else {

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

            }

        }

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

        }
    });
}

From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

private void inflateInterestCalculationPeriodSpinner(ResponseBody result) {

    final List<InterestCalculationPeriodType> interestCalculationPeriodType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> interestCalculationPeriodTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {/*  www  .  j  a  v a  2s  . co  m*/
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("interestCalculationPeriodTypeOptions")) {
            JSONArray interestCalculationPeriodTypes = obj.getJSONArray("interestCalculationPeriodTypeOptions");
            for (int i = 0; i < interestCalculationPeriodTypes.length(); i++) {
                JSONObject interestCalculationPeriodTypeObject = interestCalculationPeriodTypes
                        .getJSONObject(i);
                InterestCalculationPeriodType interestCalculationPeriod = new InterestCalculationPeriodType();
                interestCalculationPeriod.setId(interestCalculationPeriodTypeObject.optInt("id"));
                interestCalculationPeriod.setValue(interestCalculationPeriodTypeObject.optString("value"));
                interestCalculationPeriodType.add(interestCalculationPeriod);
                interestCalculationPeriodTypeNames.add(interestCalculationPeriodTypeObject.optString("value"));
                interestCalculationPeriodTypeIdHashMap.put(interestCalculationPeriod.getValue(),
                        interestCalculationPeriod.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> interestCalculationPeriodTypeAdapter = new ArrayAdapter<>(getActivity(),
            layout.simple_spinner_item, interestCalculationPeriodTypeNames);

    interestCalculationPeriodTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
    sp_interestcalculationperiod.setAdapter(interestCalculationPeriodTypeAdapter);
    sp_interestcalculationperiod.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            interestCalculationPeriodTypeId = interestCalculationPeriodTypeIdHashMap
                    .get(interestCalculationPeriodTypeNames.get(i));
            Log.d("interestCalculation " + interestCalculationPeriodTypeNames.get(i),
                    String.valueOf(interestCalculationPeriodTypeId));
            if (interestCalculationPeriodTypeId != -1) {

            } else {

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

            }

        }

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

        }
    });
}

From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

private void inflatetransactionProcessingStrategySpinner(ResponseBody result) {

    final List<TransactionProcessingStrategy> transactionProcessingStrategyType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> transactionProcessingStrategyTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {/*  w  w w.ja  v  a 2  s  .co  m*/
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("transactionProcessingStrategyOptions")) {
            JSONArray transactionProcessingStrategyTypes = obj
                    .getJSONArray("transactionProcessingStrategyOptions");
            for (int i = 0; i < transactionProcessingStrategyTypes.length(); i++) {
                JSONObject transactionProcessingStrategyTypeObject = transactionProcessingStrategyTypes
                        .getJSONObject(i);
                TransactionProcessingStrategy transactionProcessingStrategy = new TransactionProcessingStrategy();
                transactionProcessingStrategy.setId(transactionProcessingStrategyTypeObject.optInt("id"));
                transactionProcessingStrategy
                        .setName(transactionProcessingStrategyTypeObject.optString("name"));
                transactionProcessingStrategyType.add(transactionProcessingStrategy);
                transactionProcessingStrategyTypeNames
                        .add(transactionProcessingStrategyTypeObject.optString("name"));
                transactionProcessingStrategyTypeIdHashMap.put(transactionProcessingStrategy.getName(),
                        transactionProcessingStrategy.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> transactionProcessingStrategyAdapter = new ArrayAdapter<>(getActivity(),
            layout.simple_spinner_item, transactionProcessingStrategyTypeNames);

    transactionProcessingStrategyAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);

    sp_repaymentstrategy.setAdapter(transactionProcessingStrategyAdapter);
    sp_repaymentstrategy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            transactionProcessingStrategyId = transactionProcessingStrategyTypeIdHashMap
                    .get(transactionProcessingStrategyTypeNames.get(i));
            Log.d("transactionProcessing " + transactionProcessingStrategyTypeNames.get(i),
                    String.valueOf(transactionProcessingStrategyId));
            if (transactionProcessingStrategyId != -1) {

            } else {

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

            }

        }

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

        }
    });
}

From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

private void inflateFrequencyPeriodSpinner(ResponseBody result) {

    final List<TermFrequencyTypeOptions> termFrequencyType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> termFrequencyTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {//  www .  java 2 s. c om
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("termFrequencyTypeOptions")) {
            JSONArray termFrequencyTypes = obj.getJSONArray("termFrequencyTypeOptions");
            for (int i = 0; i < termFrequencyTypes.length(); i++) {
                JSONObject termFrequencyTypeObject = termFrequencyTypes.getJSONObject(i);
                TermFrequencyTypeOptions termFrequency = new TermFrequencyTypeOptions();
                termFrequency.setId(termFrequencyTypeObject.optInt("id"));
                termFrequency.setValue(termFrequencyTypeObject.optString("value"));
                termFrequencyType.add(termFrequency);
                termFrequencyTypeNames.add(termFrequencyTypeObject.optString("value"));
                termFrequencyTypeIdHashMap.put(termFrequency.getValue(), termFrequency.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> termFrequencyTypeAdapter = new ArrayAdapter<>(getActivity(),
            layout.simple_spinner_item, termFrequencyTypeNames);
    termFrequencyTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
    sp_payment_periods.setAdapter(termFrequencyTypeAdapter);
    sp_payment_periods.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

            loanTermFrequency = termFrequencyTypeIdHashMap.get(termFrequencyTypeNames.get(i));
            Log.d("termFrequencyTypeId" + termFrequencyTypeNames.get(i), String.valueOf(loanTermFrequency));
            if (loanTermFrequency != -1) {

            } else {

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

        }

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

        }
    });
}

From source file:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

@Override
public void showLoanPurposeSpinner(ResponseBody result) {

    mResponse = result;//from w  ww . j a va2  s  .  c o m

    inflateFrequencyPeriodSpinner(mResponse);
    inflateAmortizationSpinner(mResponse);
    inflateInterestCalculationPeriodSpinner(mResponse);
    //inflaterepaymentFrequencyTypeOptionsSpinner();
    inflatetransactionProcessingStrategySpinner(mResponse);

    final List<LoanPurposeOptions> loanPurposeOptionsType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> loanPurposeOptionsTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("loanPurposeOptions")) {
            JSONArray loanPurposeOptionsTypes = obj.getJSONArray("loanPurposeOptions");
            for (int i = 0; i < loanPurposeOptionsTypes.length(); i++) {
                JSONObject loanPurposeOptionsTypesObject = loanPurposeOptionsTypes.getJSONObject(i);
                LoanPurposeOptions loanpurpose = new LoanPurposeOptions();
                loanpurpose.setId(loanPurposeOptionsTypesObject.optInt("id"));
                loanpurpose.setName(loanPurposeOptionsTypesObject.optString("name"));
                loanPurposeOptionsType.add(loanpurpose);
                loanPurposeOptionsTypeNames.add(loanPurposeOptionsTypesObject.optString("name"));
                loanPurposeNameIdHashMap.put(loanpurpose.getName(), loanpurpose.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> loanPTypeAdapter = new ArrayAdapter<>(getActivity(), layout.simple_spinner_item,
            loanPurposeOptionsTypeNames);

    loanPTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
    sp_loan_purpose.setAdapter(loanPTypeAdapter);
    sp_loan_purpose.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            loanPurposeId = loanPurposeNameIdHashMap.get(loanPurposeOptionsTypeNames.get(i));
            Log.d("loanpurpose" + loanPurposeOptionsTypeNames.get(i), String.valueOf(loanPurposeId));
            if (loanPurposeId != -1) {

            } else {

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

            }

        }

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

        }
    });
}

From source file:cgeo.geocaching.connector.gc.GCParser.java

private static List<LogEntry> parseLogs(final boolean friends, String rawResponse) {
    final List<LogEntry> logs = new ArrayList<LogEntry>();

    // for non logged in users the log book is not shown
    if (StringUtils.isBlank(rawResponse)) {
        return logs;
    }//from  w ww. j  av  a  2s.  c o m

    try {
        final JSONObject resp = new JSONObject(rawResponse);
        if (!resp.getString("status").equals("success")) {
            Log.e("GCParser.loadLogsFromDetails: status is " + resp.getString("status"));
            return null;
        }

        final JSONArray data = resp.getJSONArray("data");

        for (int index = 0; index < data.length(); index++) {
            final JSONObject entry = data.getJSONObject(index);

            // FIXME: use the "LogType" field instead of the "LogTypeImage" one.
            final String logIconNameExt = entry.optString("LogTypeImage", ".gif");
            final String logIconName = logIconNameExt.substring(0, logIconNameExt.length() - 4);

            long date = 0;
            try {
                date = GCLogin.parseGcCustomDate(entry.getString("Visited")).getTime();
            } catch (final ParseException e) {
                Log.e("GCParser.loadLogsFromDetails: failed to parse log date.");
            }

            // TODO: we should update our log data structure to be able to record
            // proper coordinates, and make them clickable. In the meantime, it is
            // better to integrate those coordinates into the text rather than not
            // display them at all.
            final String latLon = entry.getString("LatLonString");
            final String logText = (StringUtils.isEmpty(latLon) ? "" : (latLon + "<br/><br/>"))
                    + TextUtils.removeControlCharacters(entry.getString("LogText"));
            final LogEntry logDone = new LogEntry(
                    TextUtils.removeControlCharacters(entry.getString("UserName")), date,
                    LogType.getByIconName(logIconName), logText);
            logDone.found = entry.getInt("GeocacheFindCount");
            logDone.friend = friends;

            final JSONArray images = entry.getJSONArray("Images");
            for (int i = 0; i < images.length(); i++) {
                final JSONObject image = images.getJSONObject(i);
                final String url = "http://imgcdn.geocaching.com/cache/log/large/"
                        + image.getString("FileName");
                final String title = TextUtils.removeControlCharacters(image.getString("Name"));
                final Image logImage = new Image(url, title);
                logDone.addLogImage(logImage);
            }

            logs.add(logDone);
        }
    } catch (final JSONException e) {
        // failed to parse logs
        Log.w("GCParser.loadLogsFromDetails: Failed to parse cache logs", e);
    }

    return logs;
}

From source file:com.github.cambierr.lorawanpacket.semtech.PushData.java

public PushData(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException {
    super(_randoms, PacketType.PUSH_DATA);
    _raw.order(ByteOrder.LITTLE_ENDIAN);

    if (_raw.remaining() < 8) {
        throw new MalformedPacketException("too short");
    }/*from   ww w.  j  av a2 s  .  c  o m*/

    gatewayEui = new byte[8];
    _raw.get(gatewayEui);

    byte[] json = new byte[_raw.remaining()];
    _raw.get(json);
    JSONObject jo;

    try {
        jo = new JSONObject(new String(json));
    } catch (JSONException ex) {
        throw new MalformedPacketException("malformed json");
    }

    stats = new ArrayList<>();
    rxpks = new ArrayList<>();

    if (jo.has("rxpk")) {
        if (!jo.get("rxpk").getClass().equals(JSONArray.class)) {
            throw new MalformedPacketException("malformed json (rxpk)");
        }
        JSONArray rxpk = jo.getJSONArray("rxpk");

        for (int i = 0; i < rxpk.length(); i++) {
            rxpks.add(new Rxpk(rxpk.getJSONObject(i)));
        }
    }

    if (jo.has("stat")) {
        if (!jo.get("stat").getClass().equals(JSONArray.class)) {
            throw new MalformedPacketException("malformed json (stat)");
        }
        JSONArray stat = jo.getJSONArray("stat");

        for (int i = 0; i < stat.length(); i++) {
            stats.add(new Stat(stat.getJSONObject(i)));
        }
    }

}

From source file:net.olejon.mdapp.LvhCategoriesAdapter.java

@Override
public void onBindViewHolder(CategoryViewHolder viewHolder, int i) {
    try {//from w w  w.j a  v  a  2s . co m
        final JSONObject categoriesJsonObject = mCategories.getJSONObject(i);

        viewHolder.card.setCardBackgroundColor(Color.parseColor(mColor));

        switch (mIcon) {
        case "lvh_urgent": {
            viewHolder.icon.setImageResource(R.drawable.ic_favorite_white_24dp);
            break;
        }
        case "lvh_symptoms": {
            viewHolder.icon.setImageResource(R.drawable.ic_stethoscope);
            break;
        }
        case "lvh_injuries": {
            viewHolder.icon.setImageResource(R.drawable.ic_healing_white_24dp);
            break;
        }
        case "lvh_administrative": {
            viewHolder.icon.setImageResource(R.drawable.ic_my_library_books_white_24dp);
            break;
        }
        }

        viewHolder.title.setText(categoriesJsonObject.getString("title"));

        viewHolder.categories.removeAllViews();

        final JSONArray itemsJsonArray = categoriesJsonObject.getJSONArray("items");

        for (int f = 0; f < itemsJsonArray.length(); f++) {
            final JSONObject categoryJsonObject = itemsJsonArray.getJSONObject(f);

            final String name = categoryJsonObject.getString("name");
            final String uri = categoryJsonObject.getString("uri");

            TextView textView = (TextView) mLayoutInflater
                    .inflate(R.layout.activity_lvh_categories_card_categories_item, null);
            textView.setText(name);

            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, MainWebViewActivity.class);
                    intent.putExtra("title", name);
                    intent.putExtra("uri", uri);
                    mContext.startActivity(intent);
                }
            });

            viewHolder.categories.addView(textView);
        }

        animateView(viewHolder.card, i);
    } catch (Exception e) {
        Log.e("LvhCategoriesAdapter", Log.getStackTraceString(e));
    }
}