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:com.xfinity.ceylon_steel.controller.CustomerController.java

public static void downloadCustomers(final Context context) {
    new AsyncTask<User, Void, JSONArray>() {

        @Override/*  w  ww  . j a  va2 s .  co  m*/
        protected void onPreExecute() {
            if (UserController.progressDialog == null) {
                UserController.progressDialog = new ProgressDialog(context);
                UserController.progressDialog.setMessage("Downloading Data");
                UserController.progressDialog.setCanceledOnTouchOutside(false);
            }
            if (!UserController.progressDialog.isShowing()) {
                UserController.progressDialog.show();
            }
        }

        @Override
        protected JSONArray doInBackground(User... users) {
            try {
                User user = users[0];
                HashMap<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("userId", user.getUserId());
                return getJsonArray(getCustomersOfUser, parameters, context);
            } catch (IOException ex) {
                Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JSONException ex) {
                Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONArray result) {
            if (UserController.atomicInteger.decrementAndGet() == 0 && UserController.progressDialog != null
                    && UserController.progressDialog.isShowing()) {
                UserController.progressDialog.dismiss();
                UserController.progressDialog = null;
            }
            if (result != null) {
                SQLiteDatabaseHelper databaseInstance = SQLiteDatabaseHelper.getDatabaseInstance(context);
                SQLiteDatabase database = databaseInstance.getWritableDatabase();
                SQLiteStatement compiledStatement = database
                        .compileStatement("replace into tbl_customer(customerId,customerName) values(?,?)");
                try {
                    database.beginTransaction();
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject customer = result.getJSONObject(i);
                        compiledStatement.bindAllArgsAsStrings(
                                new String[] { Integer.toString(customer.getInt("customerId")),
                                        customer.getString("customerName") });
                        long response = compiledStatement.executeInsert();
                        if (response == -1) {
                            return;
                        }
                    }
                    database.setTransactionSuccessful();
                    Toast.makeText(context, "Customers downloaded successfully", Toast.LENGTH_SHORT).show();
                } catch (JSONException ex) {
                    Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
                    Toast.makeText(context, "Unable parse customers", Toast.LENGTH_SHORT).show();
                } finally {
                    database.endTransaction();
                    databaseInstance.close();
                }
            } else {
                Toast.makeText(context, "Unable to download customers", Toast.LENGTH_SHORT).show();
            }
        }

    }.execute(UserController.getAuthorizedUser(context));
}

From source file:cn.newgxu.android.notty.service.FetchService.java

@Override
protected void onHandleIntent(Intent intent) {
    //      int method = intent.getIntExtra("method", RESTMethod.GET);
    //      switch (method) {
    //      case RESTMethod.GET:
    //         break;
    //      case RESTMethod.POST:
    //         Map<String, Object> params = new HashMap<String, Object>();
    //         params.put(C.notice.TITLE, intent.getStringExtra(C.notice.TITLE));
    //         params.put(C.notice.CONTENT, intent.getStringExtra(C.notice.CONTENT));
    //         L.d(TAG, "post result: %s", result);
    //         ContentValues values = new ContentValues();
    //         values.put(C.notice.TITLE, intent.getStringExtra(C.notice.TITLE));
    //         values.put(C.notice.CONTENT, intent.getStringExtra(C.notice.CONTENT));
    //         getContentResolver().insert(Uri.parse(C.BASE_URI + C.NOTICES), values);
    //         return;
    //      default:
    //         break;
    //      }/*  w  w w  . j  a va  2 s  .  com*/
    if (NetworkUtils.connected(getApplicationContext())) {
        Cursor c = getContentResolver().query(Uri.parse(C.BASE_URI + C.NOTICES), C.notice.LATEST_NOTICE_ID,
                null, null, null);
        String uri = intent.getStringExtra(C.URI);
        if (c.moveToNext()) {
            uri += "&local_nid=" + c.getLong(0);
        }
        Log.d(TAG, String.format("uri: %s", uri));
        JSONObject result = RESTMethod.get(uri);
        L.d(TAG, "json: %s", result);
        try {
            JSONArray notices = result.getJSONArray(C.NOTICES);
            ContentValues[] noticeValues = new ContentValues[notices.length()];
            ContentValues[] userValues = new ContentValues[notices.length()];
            for (int i = 0; i < userValues.length; i++) {
                JSONObject n = notices.getJSONObject(i);
                JSONObject u = n.getJSONObject(C.USER);
                noticeValues[i] = Processor.json2Notice(n);
                userValues[i] = Processor.json2User(u);
            }
            String[] uris = intent.getStringArrayExtra("uris");
            getContentResolver().bulkInsert(Uri.parse(uris[0]), noticeValues);
            getContentResolver().bulkInsert(Uri.parse(uris[1]), userValues);

            final int newerCount = notices.length();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), getString(R.string.newer_count, newerCount),
                            Toast.LENGTH_SHORT).show();
                }
            });
        } catch (JSONException e) {
            throw new RuntimeException("ERROR when resolving json -> " + result, e);
        }
    } else {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), R.string.network_down, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

From source file:cn.kangeqiu.kq.activity.MainActivity.java

/**
 * ?????.//ww  w  .j  a v a 2s . c  o m
 */
public void updateUnreadLabel() {
    ArrayList<NameValuePair> pair = new ArrayList<NameValuePair>();
    pair.add(new BasicNameValuePair("app_action", "2025"));
    pair.add(new BasicNameValuePair("app_platform", "0"));
    pair.add(new BasicNameValuePair("u_uid", AppConfig.getInstance().getPlayerId() + ""));
    new WebRequestUtil().execute(true, AppConfig.getInstance().makeUrl(Integer.parseInt("2025")), pair,
            new MCHttpCallBack() {
                @Override
                public void onSuccess(MCHttpResp resp) {
                    super.onSuccess(resp);
                    try {

                        String resultCode = resp.getJson().getString("result_code");
                        if (resultCode.equals("0")) {
                            JSONArray records = (JSONArray) resp.getJson().getJSONArray("records");
                            int counts = 0;
                            for (int i = 0; i < records.length(); i++) {
                                // ?
                                String unread_count = records.getJSONObject(i).getString("unread_count");
                                if (unread_count == null || unread_count.length() == 0)
                                    unread_count = "0";
                                int count = Integer.parseInt(unread_count);
                                counts += count;
                            }
                            updateAllUnreadLabel(counts);
                        } else {
                            Toast.makeText(context, resp.getJson().getString("message"), Toast.LENGTH_SHORT)
                                    .show();
                        }

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(MCHttpResp resp) {
                    super.onError(resp);
                    Toast.makeText(MainActivity.this, resp.getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            });

}

From source file:com.goliathonline.android.kegbot.io.RemoteKegsHandler.java

/** {@inheritDoc} */
@Override//from  www .  ja  v  a2  s  .  c  o  m
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {

    if (parser.has("result")) {
        JSONObject events = parser.getJSONObject("result");
        JSONArray resultArray = events.getJSONArray("kegs");
        int numKegs = resultArray.length();
        List<String> kegIDs = new ArrayList<String>();

        JSONObject keg, kegInfo;
        for (int i = 0; i < numKegs; i++) {
            keg = resultArray.getJSONObject(i);
            kegInfo = keg.getJSONObject("keg");
            kegIDs.add(kegInfo.getString("id"));
            ///TODO: new api allows all infromation to be parsed here, and not in a seperate call.
        }
        considerUpdate(kegIDs, Kegs.CONTENT_URI, resolver);
    }

    return Lists.newArrayList();
}

From source file:cc.redpen.server.api.RedPenResourceTest.java

public void testJSValidatorRuns() throws Exception {
    if (new File("redpen-server").exists()) {
        System.setProperty("REDPEN_HOME", "redpen-server/src/test");
    } else {/*from   ww w  .j a v  a2s . com*/
        System.setProperty("REDPEN_HOME", "src/test");
    }
    MockHttpServletRequest request = constructMockRequest("POST", "/document/validate/json", WILDCARD,
            APPLICATION_JSON);
    request.setContent(String.format(
            "{\"document\":\"Test, this is a test.\",\"format\":\"json2\",\"documentParser\":\"PLAIN\",\"config\":{\"lang\":\"en\",\"validators\":{\"JavaScript\":{\"properties\":{\"script-path\":\"%s\"}}}}}",
            "resources/js").getBytes());
    MockHttpServletResponse response = invoke(request);

    assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus());
    JSONArray errors = new JSONObject(response.getContentAsString()).getJSONArray("errors");
    assertTrue(errors.length() > 0);
    for (int i = 0; i < errors.length(); ++i) {
        JSONObject o = errors.getJSONObject(i).getJSONArray("errors").getJSONObject(0);
        assertEquals("[pass.js] called", o.getString("message"));
    }
}

From source file:com.norman0406.slimgress.API.Item.ItemModMultihack.java

public ItemModMultihack(JSONArray json) throws JSONException {
    super(ItemBase.ItemType.ModMultihack, json);

    JSONObject item = json.getJSONObject(2);
    JSONObject modResource = item.getJSONObject("modResource");
    JSONObject stats = modResource.getJSONObject("stats");
    mBurnoutInsulation = Integer.parseInt(stats.getString("BURNOUT_INSULATION"));
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createSearchDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_search_tools,
            R.string.search_tools_title);

    final ScrollView scrollView = (ScrollView) dialog.findViewById(R.id.search_tools_dialog_scroll_view);
    final AutoCompleteTextView inputField = (AutoCompleteTextView) dialog
            .findViewById(R.id.search_tools_input_field);
    final LinearLayout rowsContainer = (LinearLayout) dialog.findViewById(R.id.search_tools_row_container);
    final Button viewInMapButton = (Button) dialog.findViewById(R.id.search_tools_view_in_map_button);
    final Button jumpToBottomButton = (Button) dialog.findViewById(R.id.search_tools_jump_to_bottom_button);
    Button dismissButton = (Button) dialog.findViewById(R.id.search_tools_dismiss_button);

    List<PropertyDescription> subscribables;
    PropertyDescription newestSubscribable = null;
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
            Locale.getDefault());
    Date cachedUpdateDateTime;/*from   w  ww  .  j  av  a  2s . com*/
    Date newestUpdateDateTime;
    SubscriptionEntry cachedEntry;
    Response response;
    final JSONArray toolsArray;
    ArrayAdapter<String> adapter;
    String format = "JSON";
    String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString() + "/FiskInfo/Offline/";
    final JSONObject tools;
    final List<String> vesselNames;
    final Map<String, List<Integer>> toolIdMap = new HashMap<>();
    byte[] data = new byte[0];

    cachedEntry = user.getSubscriptionCacheEntry(getString(R.string.fishing_facility_api_name));

    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        subscribables = barentswatchApi.getApi().getSubscribable();
        for (PropertyDescription subscribable : subscribables) {
            if (subscribable.ApiName.equals(getString(R.string.fishing_facility_api_name))) {
                newestSubscribable = subscribable;
                break;
            }
        }
    } else if (cachedEntry == null) {
        Dialog infoDialog = dialogInterface.getAlertDialog(getActivity(), R.string.tools_search_no_data_title,
                R.string.tools_search_no_data, -1);

        infoDialog.show();
        return;
    }

    if (cachedEntry != null) {
        try {
            cachedUpdateDateTime = simpleDateFormat
                    .parse(cachedEntry.mLastUpdated.equals(getActivity().getString(R.string.abbreviation_na))
                            ? "2000-00-00T00:00:00"
                            : cachedEntry.mLastUpdated);
            newestUpdateDateTime = simpleDateFormat
                    .parse(newestSubscribable != null ? newestSubscribable.LastUpdated : "2000-00-00T00:00:00");

            if (cachedUpdateDateTime.getTime() - newestUpdateDateTime.getTime() < 0) {
                response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
                try {
                    data = FiskInfoUtility.toByteArray(response.getBody().in());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                        newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath,
                        false)) {
                    SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
                    entry.mLastUpdated = newestSubscribable.LastUpdated;
                    user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
                    user.writeToSharedPref(getActivity());
                }
            } else {
                String directoryFilePath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
                        + "/FiskInfo/Offline/";

                File file = new File(directoryFilePath + newestSubscribable.Name + ".JSON");
                StringBuilder jsonString = new StringBuilder();
                BufferedReader bufferReader = null;

                try {
                    bufferReader = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = bufferReader.readLine()) != null) {
                        jsonString.append(line);
                        jsonString.append('\n');
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bufferReader != null) {
                        try {
                            bufferReader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                data = jsonString.toString().getBytes();
            }

        } catch (ParseException e) {
            e.printStackTrace();
            Log.e(TAG, "Invalid datetime provided");
        }
    } else {
        response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
        try {
            data = FiskInfoUtility.toByteArray(response.getBody().in());
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath, false)) {
            SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
            entry.mLastUpdated = newestSubscribable.LastUpdated;
            user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
        }
    }

    try {
        tools = new JSONObject(new String(data));
        toolsArray = tools.getJSONArray("features");
        vesselNames = new ArrayList<>();
        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, vesselNames);

        for (int i = 0; i < toolsArray.length(); i++) {
            JSONObject feature = toolsArray.getJSONObject(i);
            String vesselName = (feature.getJSONObject("properties").getString("vesselname") != null
                    && !feature.getJSONObject("properties").getString("vesselname").equals("null"))
                            ? feature.getJSONObject("properties").getString("vesselname")
                            : getString(R.string.vessel_name_unknown);
            List<Integer> toolsIdList = toolIdMap.get(vesselName) != null ? toolIdMap.get(vesselName)
                    : new ArrayList<Integer>();

            if (vesselName != null && !vesselNames.contains(vesselName)) {
                vesselNames.add(vesselName);
            }

            toolsIdList.add(i);
            toolIdMap.put(vesselName, toolsIdList);
        }

        inputField.setAdapter(adapter);
    } catch (JSONException e) {
        dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                R.string.search_tools_init_info, -1).show();
        Log.e(TAG, "JSON parse error");
        e.printStackTrace();

        return;
    }

    if (searchToolsButton.getTag() != null) {
        inputField.requestFocus();
        inputField.setText(searchToolsButton.getTag().toString());
        inputField.selectAll();
    }

    inputField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selectedVesselName = ((TextView) view).getText().toString();
            List<Integer> selectedTools = toolIdMap.get(selectedVesselName);
            Gson gson = new Gson();
            String toolSetDateString;
            Date toolSetDate;

            rowsContainer.removeAllViews();

            for (int toolId : selectedTools) {
                JSONObject feature;
                Feature toolFeature;

                try {
                    feature = toolsArray.getJSONObject(toolId);

                    if (feature.getJSONObject("geometry").getString("type").equals("LineString")) {
                        toolFeature = gson.fromJson(feature.toString(), LineFeature.class);
                    } else {
                        toolFeature = gson.fromJson(feature.toString(), PointFeature.class);
                    }

                    toolSetDateString = toolFeature.properties.setupdatetime != null
                            ? toolFeature.properties.setupdatetime
                            : "2038-00-00T00:00:00";
                    toolSetDate = simpleDateFormat.parse(toolSetDateString);

                } catch (JSONException | ParseException e) {
                    dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                            R.string.search_tools_init_info, -1).show();
                    e.printStackTrace();

                    return;
                }

                ToolSearchResultRow row = rowsInterface.getToolSearchResultRow(getActivity(),
                        R.drawable.ikon_kystfiske, toolFeature);
                long toolTime = System.currentTimeMillis() - toolSetDate.getTime();
                long highlightCutoff = ((long) getResources().getInteger(R.integer.milliseconds_in_a_day))
                        * ((long) getResources().getInteger(R.integer.days_to_highlight_active_tool));

                if (toolTime > highlightCutoff) {
                    int colorId = ContextCompat.getColor(getActivity(), R.color.error_red);
                    row.setDateTextViewTextColor(colorId);
                }

                rowsContainer.addView(row.getView());
            }

            viewInMapButton.setEnabled(true);
            inputField.setTag(selectedVesselName);
            searchToolsButton.setTag(selectedVesselName);
            jumpToBottomButton.setVisibility(View.VISIBLE);
            jumpToBottomButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.scrollTo(0, rowsContainer.getBottom());
                        }
                    });
                }
            });

        }
    });

    viewInMapButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String vesselName = inputField.getTag().toString();
            highlightToolsInMap(vesselName);

            dialog.dismiss();
        }
    });

    dismissButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    dialog.show();
}

From source file:com.liferay.mobile.android.v62.contact.ContactService.java

public JSONObject getContact(long contactId) throws Exception {
    JSONObject _command = new JSONObject();

    try {//from w  w w.  j a  v a2  s .co  m
        JSONObject _params = new JSONObject();

        _params.put("contactId", contactId);

        _command.put("/contact/get-contact", _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.bindez.nlp.converter.RabbitConverter.java

public static String replace_with_rule(String rule, String output) {

    try {/*w  ww  .j  a v a2  s  .  c  om*/
        JSONArray rule_array = new JSONArray(rule);
        int max_loop = rule_array.length();

        //because of JDK 7 bugs in Android
        output = output.replace("null", "\uFFFF\uFFFF");

        for (int i = 0; i < max_loop; i++) {

            JSONObject obj = rule_array.getJSONObject(i);
            String from = obj.getString("from");
            String to = obj.getString("to");

            output = output.replaceAll(from, to);
            output = output.replace("null", "");

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    output = output.replace("\uFFFF\uFFFF", "null");
    return output;
}

From source file:com.jennifer.ui.chart.grid.DateGrid.java

private void initDomain() {

    if (has("target") && !has("domain")) {

        if (options.get("target") instanceof String) {
            JSONArray list = new JSONArray();
            list.put(options.getString("target"));
            options.put("target", list);
        }//from   w ww. ja v  a  2  s . co  m

        JSONArray target = (JSONArray) options.getJSONArray("target");
        JSONArray domain = new JSONArray();
        JSONArray data = chart.data();

        long min = 0;
        long max = 0;

        boolean hasMin = options.has("min");
        boolean hasMax = options.has("max");

        for (int i = 0, len = target.length(); i < len; i++) {
            String key = target.getString(i);

            for (int index = 0, dataLength = data.length(); index < dataLength; index++) {
                JSONObject row = data.getJSONObject(index);

                long value = 0;

                if (row.get(key) instanceof Date) {
                    value = ((Date) row.get(key)).getTime();
                } else {
                    value = row.getLong(key);
                }

                if (!hasMin) {
                    min = value;
                    hasMin = true;
                } else if (min > value)
                    min = value;

                if (!hasMax) {
                    max = value;
                    hasMax = true;
                } else if (max < value)
                    max = value;
            }

        }

        options.put("max", max);
        options.put("min", min);

        domain.put(min).put(max);

        if (options.optBoolean("reverse", false)) {
            JSONUtil.reverse(domain);
        }

        options.put("domain", domain);

    }

}