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:com.kevinquan.android.utils.JSONUtils.java

/**
 * Retrieve a JSON array stored at the provided key from the provided JSON object
 * @param obj The JSON object to retrieve from
 * @param key The key to retrieve/* w  ww .  ja v a  2  s. c om*/
 * @return the array stored in the key, or null if the key doesn't exist
 */
public static JSONArray safeGetArrayFromObject(JSONObject obj, String key) {
    if (obj == null || TextUtils.isEmpty(key))
        return null;
    if (obj.has(key)) {
        try {
            return obj.getJSONArray(key);
        } catch (JSONException e) {
            Log.w(TAG, "Could not get Array from JSONArray from key " + key, e);
        }
    }
    return null;
}

From source file:org.nikki.omegle.Omegle.java

/**
 * Opens a new omegle session. Note: This CONNECTS THE SESSION!
 * /*  w  w  w  .  ja  v a2 s .co  m*/
 * @param mode
 *            The omegle chat mode
 * @param objs
 *            The objects. If mode = SPY_QUESTION, param 1 should be the
 *            question. Parameters are checked, so you may pass event
 *            listeners through here.
 * 
 * @return The newly created session
 * @throws OmegleException
 *             If an error occurred while attempting to open, always due to
 *             an IOException
 */
public OmegleSession openSession(OmegleMode mode, Object... objs) throws OmegleException {
    try {
        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("rcs", "1");
        vars.put("firstevents", firstEvents ? "1" : "0");

        if (mode == OmegleMode.SPY) {
            vars.put("wantsspy", "1");
        } else if (mode == OmegleMode.SPY_QUESTION) {
            if (objs.length > 0) {
                if (objs[0] instanceof String) {
                    vars.put("ask", objs[0].toString());
                } else {
                    throw new OmegleException("The question MUST be passed as the first parameter!");
                }
            } else {
                throw new OmegleException("You cannot open a spy question session without a question!");
            }
        }

        URL url = new URL(OPEN_URL + "?" + HttpUtil.implode(vars));

        JSONObject resp = new JSONObject(HttpUtil.post(url, ""));

        if (!resp.has("clientID")) {
            throw new OmegleException("Omegle didn't return a client id!");
        }

        OmegleSession session = new OmegleSession(this, resp.getString("clientID"));

        for (Object obj : objs) {
            if (obj instanceof OmegleEventListener) {
                session.addListener((OmegleEventListener) obj);
            }
        }

        if (resp.has("events")) {
            session.parseEvents(resp.getJSONArray("events"));
        }

        synchronized (sessions) {
            sessions.add(session);
        }

        return session;
    } catch (IOException e) {
        throw new OmegleException(e);
    } catch (JSONException e) {
        throw new OmegleException(e);
    }
}

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  .  ja v  a  2s . 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 {//ww  w. java 2s.  com
        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 {//  ww w  .jav  a2s  .  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 {/*from ww  w  .  j av a  2s . 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("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 v  a 2s. co 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:sh.calaba.driver.client.model.impl.WebViewImpl.java

public String getPageSource() {
    JSONObject response = executeCalabashCommand(CalabashCommands.GET_WEBVIEW_PAGE_SOURCE);
    try {/*from w ww . j a  v  a2 s. c om*/
        return response.getJSONArray("bonusInformation").optString(0);
    } catch (JSONException e) {

        return null;
    }
}

From source file:com.googlecode.goclipse.tooling.oracle.OraclePackageDescribeParser.java

protected JSONArray getOptionalJSONArray(JSONObject packageObj, String key) throws JSONException {
    if (!packageObj.has(key)) {
        return null;
    }//  ww w  . j a  v  a 2s .com
    return packageObj.getJSONArray(key);
}

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 ww  w .  j a  v a  2s.c  om*/

    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;
}