Example usage for org.json JSONArray getString

List of usage examples for org.json JSONArray getString

Introduction

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

Prototype

public String getString(int index) throws JSONException 

Source Link

Document

Get the string associated with an index.

Usage

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

public void onRestRequestComplete(Methods method, JSONObject result) {
    if (method == Methods.phone) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    SharedPreferences.Editor editor = getSharedPreferences(APO.PREF_FILE_NAME, MODE_PRIVATE)
                            .edit();//from   w ww  . j  a  v a2  s.  co  m
                    editor.putLong("updateTime", result.getLong("updateTime"));
                    editor.commit();
                    int numbros = result.getInt("numBros");
                    JSONArray caseID = result.getJSONArray("caseID");
                    JSONArray first = result.getJSONArray("first");
                    JSONArray last = result.getJSONArray("last");
                    JSONArray phone = result.getJSONArray("phone");
                    JSONArray family = result.getJSONArray("family");
                    ContentValues values;
                    for (int i = 0; i < numbros; i++) {
                        values = new ContentValues();
                        values.put("_id", caseID.getString(i));
                        values.put("first", first.getString(i));
                        values.put("last", last.getString(i));
                        values.put("phone", phone.getString(i));
                        values.put("family", family.getString(i));
                        database.replace("phoneDB", null, values);
                    }
                    loadTable();
                } else if (requestStatus.compareTo("timestamp invalid") == 0) {
                    Toast msg = Toast.makeText(this, "Invalid timestamp.  Please try again.",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("HMAC invalid") == 0) {
                    Auth.loggedIn = false;
                    Toast msg = Toast.makeText(this,
                            "You have been logged out by the server.  Please log in again.", Toast.LENGTH_LONG);
                    msg.show();
                    finish();
                } else {
                    Toast msg = Toast.makeText(this, "Invalid requestStatus", Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:com.baoyz.bigbang.segment.NetworkParser.java

@Override
public void parse(String text, final Callback<String[]> callback) {
    if (callback == null) {
        return;/*from  www. jav a2 s  .  co  m*/
    }
    Request request = createRequest(text);
    mClient.newCall(request).enqueue(new okhttp3.Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            callback.error(e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            final String string = response.body().string();
            final JSONArray array;
            try {
                array = new JSONArray(string);
                String[] result = new String[array.length()];
                for (int i = 0; i < array.length(); i++) {
                    result[i] = array.getString(i);
                }
                callback.finish(result);
            } catch (JSONException e) {
                e.printStackTrace();
                callback.error(e);
            }
        }
    });
}

From source file:com.port.ocean.shipping.data.VehiclePassedData.java

@Override
protected void onExtractData(JSONObject jsonData) throws Exception {
    JSONArray jsonArray = jsonData.getJSONArray(DATA_TAG);

    dataList = new ArrayList<>();
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONArray row = jsonArray.getJSONArray(i);

        if (row.length() > 4) {
            VehiclePassed data = new VehiclePassed();
            data.setLicensePlateNumber(row.getString(0));
            data.setLocation(row.getString(1));
            data.setStorage(row.getString(2));
            data.setAuditTime(row.getString(3));
            data.setAttention("1".equals(row.getString(4)));

            dataList.add(data);/*w w  w.j av  a2  s . c o  m*/
        }
    }
}

From source file:run.ace.NativeHost.java

public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    // Don't run any of these if the current activity is finishing.
    if (_activity.isFinishing())
        return true;

    if (action.equals("send")) {
        this.send(args, callbackContext);
    } else if (action.equals("loadXbf")) {
        this.loadXbf(args.getString(0), callbackContext);
    } else if (action.equals("initialize")) {
        ////from   w ww. j  a  va2s.co m
        // Do not initialize unsupported android versions
        //
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
            return true;
        }

        OutgoingMessages.setCallbackContext(callbackContext);
        /* TODO: No startup markup
        if (_startupMarkup != null) {
        // Send the bytes back to the managed side.
        // Do it directly instead of using OutgoingMessages.raiseEvent
        // Because otherwise it gets marshaled as an array instead of an ArrayBuffer
          PluginResult r = new PluginResult(PluginResult.Status.OK, _startupMarkup);
          r.setKeepCallback(true);
        callbackContext.sendPluginResult(r);
        _startupMarkup = null;
        }
        */
    } else if (action.equals("loadPlatformSpecificMarkup")) {
        this.loadPlatformSpecificMarkup(args.getString(0), callbackContext);
    } else if (action.equals("getAndroidId")) {
        this.getAndroidId(args.getString(0), callbackContext);
    } else if (action.equals("startAndroidActivity")) {
        this.startAndroidActivity(args.getString(0), callbackContext);
    } else if (action.equals("setPopupsCloseOnHtmlNavigation")) {
        this.setPopupsCloseOnHtmlNavigation(args.getBoolean(0), callbackContext);
    } else if (action.equals("isSupported")) {
        boolean supported = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT;
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, supported));
    } else {
        return false;
    }

    return true;
}

From source file:pt.webdetails.cdv.operations.PushWarningsHandler.java

private static Alert getAlertFromEvent(PluginEvent event, JSONObject request) {

    String msg = event.toString();
    String subject = "[" + getLevel(event) + "] " + event.getPlugin();
    if ("QueryTooLong".equals(event.getEventType())) {

        try {//  w  ww .j a  va 2s  .  c  om
            JSONObject queryInfo = new JSONObject(request.getString("queryInfo"));
            msg = "Query " + queryInfo.getString("dataAccessId") + " in " + request.getString("name") + " took "
                    + request.getString("duration") + " seconds. \n\n Actual Query: "
                    + queryInfo.getString("query") + " \n\nParameters: " + queryInfo.getString("parameters");
            subject = "CDA Slow Query Alert: " + queryInfo.getString("dataAccessId") + " took "
                    + request.getString("duration") + " seconds";
        } catch (JSONException jsoe) {
            logger.error("Error while getting alert message from original event", jsoe);
        }
    } else if ("QueryError".equals(event.getEventType())) {
        try {
            JSONObject queryInfo = new JSONObject(request.getString("queryInfo"));
            msg = "Query " + queryInfo.getString("dataAccessId") + " in " + request.getString("name")
                    + " has failed with exception " + request.getString("message") + " \n\n" + "Stack Trace: ";

            JSONArray sTrace = (JSONArray) request.get("stackTrace");
            for (int i = 0; i < sTrace.length(); i++) {
                msg += "\n" + sTrace.getString(i);
            }
            msg += "\n\n Actual Query: " + queryInfo.getString("query") + " \n\nParameters: "
                    + queryInfo.getString("parameters");
            subject = "CDA ERROR: Query " + queryInfo.getString("dataAccessId") + " in "
                    + request.getString("name") + " has failed with exception " + request.getString("message");
        } catch (JSONException jsoe) {
            logger.error("Error while getting alert message from original event", jsoe);
        }
    }

    return new Alert(getLevel(event), event.getPlugin(), event.getName(), msg, subject);
}

From source file:fr.haploid.webservices.WebServicesTask.java

@Override
protected JSONObject doInBackground(Void... params) {
    try {// w  w  w  . ja  v a 2 s . c om
        if (mSendCacheResult) {
            JSONObject cacheResultMessage = new JSONObject();
            cacheResultMessage.put(Cobalt.kJSType, Cobalt.JSTypePlugin);
            cacheResultMessage.put(Cobalt.kJSPluginName, JSPluginNameWebservices);

            JSONObject storedData = new JSONObject();
            storedData.put(kJSCallId, mCallId);
            cacheResultMessage.put(Cobalt.kJSData, storedData);

            int storageSize = WebServicesData.getCountItem();
            if (storageSize > 0) {
                if (mStorageKey != null) {
                    String storedValue = WebServicesPlugin.storedValueForKey(mStorageKey, mFragment);

                    if (storedValue != null) {
                        try {
                            storedData.put(Cobalt.kJSData, WebServicesPlugin
                                    .treatData(new JSONObject(storedValue), mProcessData, mFragment));

                            cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageResult);
                            //cacheResultMessage.put(Cobalt.kJSData, storedData);
                        } catch (JSONException exception) {
                            if (Cobalt.DEBUG) {
                                Log.e(WebServicesPlugin.TAG,
                                        TAG + " - doInBackground: value parsing failed for key " + mStorageKey
                                                + ". Value: " + storedValue);
                                exception.printStackTrace();
                            }

                            cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                            storedData.put(kJSText, JSTextUnknownError);
                        }
                    } else {
                        if (Cobalt.DEBUG)
                            Log.w(WebServicesPlugin.TAG,
                                    TAG + " - doInBackground: value not found in cache for key " + mStorageKey
                                            + ".");

                        cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                        storedData.put(kJSText, JSTextNotFound);
                    }
                } else {
                    cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                    storedData.put(kJSText, JSTextUnknownError);

                }
            } else {
                if (Cobalt.DEBUG)
                    Log.w(WebServicesPlugin.TAG, TAG + " - doInBackground: cache is empty.");

                cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                storedData.put(kJSText, JSTextEmpty);
            }
            cacheResultMessage.put(Cobalt.kJSData, storedData);

            mFragment.sendMessage(cacheResultMessage);
        }

        if (mUrl != null && mType != null) {
            // TODO: later, use Helper
            /*
            responseData = WebServicesHelper.downloadFromServer(data.getString(URL), data.getJSONObject(PARAMS), data.getString(TYPE));
            if (responseData != null) {
            responseHolder.put(TEXT, responseData.getResponseData());
            responseHolder.put(STATUS_CODE, responseData.getStatusCode());
            responseHolder.put(WS_SUCCESS, responseData.isSuccess());
            responseHolder.put(CALL_WS, true);
            }
            */

            Uri.Builder builder = new Uri.Builder();
            builder.encodedPath(mUrl);

            if (!mParams.equals("") && mType.equalsIgnoreCase(JSTypeGET))
                builder.encodedQuery(mParams);

            JSONObject response = new JSONObject();
            response.put(kJSSuccess, false);

            try {
                URL url = new URL(builder.build().toString());

                try {
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    if (mTimeout > 0)
                        urlConnection.setConnectTimeout(mTimeout);
                    urlConnection.setRequestMethod(mType);
                    urlConnection.setDoInput(true);

                    if (mHeaders != null) {
                        JSONArray names = mHeaders.names();

                        if (names != null) {
                            int length = names.length();

                            for (int i = 0; i < length; i++) {
                                String name = names.getString(i);
                                urlConnection.setRequestProperty(name, mHeaders.get(name).toString());
                            }
                        }
                    }

                    if (!mParams.equals("") && !mType.equalsIgnoreCase(JSTypeGET)) {
                        urlConnection.setDoOutput(true);

                        OutputStream outputStream = urlConnection.getOutputStream();
                        BufferedWriter writer = new BufferedWriter(
                                new OutputStreamWriter(outputStream, "UTF-8"));
                        writer.write(mParams);
                        writer.flush();
                        writer.close();
                        outputStream.close();
                    }

                    urlConnection.connect();

                    int responseCode = urlConnection.getResponseCode();
                    if (responseCode != -1) {
                        response.put(kJSStatusCode, responseCode);
                        if (responseCode < 400)
                            response.put(kJSSuccess, true);
                    }

                    try {
                        InputStream inputStream;
                        if (responseCode >= 400 && responseCode < 600)
                            inputStream = urlConnection.getErrorStream();
                        else
                            inputStream = urlConnection.getInputStream();

                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        StringBuffer buffer = new StringBuffer();
                        String line;

                        while ((line = reader.readLine()) != null) {
                            buffer.append(line).append("\n");
                        }
                        if (buffer.length() != 0)
                            response.put(kJSText, buffer.toString());
                    } catch (IOException exception) {
                        if (Cobalt.DEBUG) {
                            Log.i(WebServicesPlugin.TAG,
                                    TAG + " - doInBackground: no DATA returned by server.");
                            exception.printStackTrace();
                        }
                    }
                } catch (ProtocolException exception) {
                    if (Cobalt.DEBUG) {
                        Log.e(WebServicesPlugin.TAG,
                                TAG + " - doInBackground: not supported request method type " + mType);
                        exception.printStackTrace();
                    }
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
                return response;
            } catch (MalformedURLException exception) {
                if (Cobalt.DEBUG) {
                    Log.e(WebServicesPlugin.TAG,
                            TAG + " - doInBackground: malformed url " + builder.build().toString() + ".");
                    exception.printStackTrace();
                }
            }
        }
    } catch (JSONException exception) {
        exception.printStackTrace();
    }

    return null;
}

From source file:com.liferay.mobile.android.v62.blogsentry.BlogsEntryService.java

public String getCompanyEntriesRss(long companyId, long displayDate, int status, int max, String type,
        double version, String displayStyle, String feedURL, String entryURL, JSONObjectWrapper themeDisplay)
        throws Exception {
    JSONObject _command = new JSONObject();

    try {/*w w  w.j  a  va 2  s . c o m*/
        JSONObject _params = new JSONObject();

        _params.put("companyId", companyId);
        _params.put("displayDate", displayDate);
        _params.put("status", status);
        _params.put("max", max);
        _params.put("type", checkNull(type));
        _params.put("version", version);
        _params.put("displayStyle", checkNull(displayStyle));
        _params.put("feedURL", checkNull(feedURL));
        _params.put("entryURL", checkNull(entryURL));
        mangleWrapper(_params, "themeDisplay", "com.liferay.portal.theme.ThemeDisplay", themeDisplay);

        _command.put("/blogsentry/get-company-entries-rss", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

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

    return _result.getString(0);
}

From source file:com.liferay.mobile.android.v62.blogsentry.BlogsEntryService.java

public String getGroupEntriesRss(long groupId, long displayDate, int status, int max, String type,
        double version, String displayStyle, String feedURL, String entryURL, JSONObjectWrapper themeDisplay)
        throws Exception {
    JSONObject _command = new JSONObject();

    try {//from   w w w  . j  ava2 s. c  o m
        JSONObject _params = new JSONObject();

        _params.put("groupId", groupId);
        _params.put("displayDate", displayDate);
        _params.put("status", status);
        _params.put("max", max);
        _params.put("type", checkNull(type));
        _params.put("version", version);
        _params.put("displayStyle", checkNull(displayStyle));
        _params.put("feedURL", checkNull(feedURL));
        _params.put("entryURL", checkNull(entryURL));
        mangleWrapper(_params, "themeDisplay", "com.liferay.portal.theme.ThemeDisplay", themeDisplay);

        _command.put("/blogsentry/get-group-entries-rss", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

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

    return _result.getString(0);
}

From source file:com.liferay.mobile.android.v62.blogsentry.BlogsEntryService.java

public String getOrganizationEntriesRss(long organizationId, long displayDate, int status, int max, String type,
        double version, String displayStyle, String feedURL, String entryURL, JSONObjectWrapper themeDisplay)
        throws Exception {
    JSONObject _command = new JSONObject();

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

        _params.put("organizationId", organizationId);
        _params.put("displayDate", displayDate);
        _params.put("status", status);
        _params.put("max", max);
        _params.put("type", checkNull(type));
        _params.put("version", version);
        _params.put("displayStyle", checkNull(displayStyle));
        _params.put("feedURL", checkNull(feedURL));
        _params.put("entryURL", checkNull(entryURL));
        mangleWrapper(_params, "themeDisplay", "com.liferay.portal.theme.ThemeDisplay", themeDisplay);

        _command.put("/blogsentry/get-organization-entries-rss", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

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

    return _result.getString(0);
}

From source file:com.jennifer.ui.util.JSONUtil.java

public static JSONObject extend(JSONObject o, JSONObject attr) {
    JSONObject newObj = new JSONObject();

    JSONArray names1 = o.names();
    if (names1 != null) {
        for (int i = 0, len = names1.length(); i < len; i++) {
            String key = names1.getString(i);
            Object value = o.get(key);

            newObj.put(key, value);//  w  ww.  j a  v  a  2s. c o  m
        }
    }

    JSONArray names = attr.names();
    if (names != null) {
        for (int i = 0, len = names.length(); i < len; i++) {
            String key = names.getString(i);
            Object value = attr.get(key);

            newObj.put(key, value);
        }
    }

    return newObj;
}