Example usage for org.json JSONArray optJSONObject

List of usage examples for org.json JSONArray optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(int index) 

Source Link

Document

Get the optional JSONObject associated with an index.

Usage

From source file:app.sunstreak.yourpisd.net.Student.java

/**
 * Uses internet every time.//from   www . j  a v  a  2s . co  m
 * 
 * @throws org.json.JSONException
 */
public int[][] loadGradeSummary() throws JSONException {
    try {
        String classId = "" + classList.getJSONObject(0).getInt("enrollmentId");
        String termId = "" + classList.getJSONObject(0).getJSONArray("terms").getJSONObject(0).getInt("termId");

        String url = "https://gradebook.pisd.edu/Pinnacle/Gradebook/InternetViewer/GradeSummary.aspx?"
                + "&EnrollmentId=" + classId + "&TermId=" + termId + "&ReportType=0&StudentId=" + studentId;

        HTTPResponse summary = Request.sendGet(url, session.cookies);
        String response = summary.getData();
        int responseCode = summary.getResponseCode();

        if (responseCode != 200)
            System.out.println("Response code: " + responseCode);

        /*
         * puts averages in classList, under each term.
         */
        Element doc = Jsoup.parse(response);
        gradeSummary = Parser.gradeSummary(doc, classList);

        matchClasses(gradeSummary);

        for (int classIndex = 0; classIndex < gradeSummary.length; classIndex++) {
            int jsonIndex = classMatch[classIndex];
            JSONArray terms = classList.getJSONObject(jsonIndex).getJSONArray("terms");

            int firstTermIndex = 0;
            int lastTermIndex = 0;

            if (terms.length() == 8) {
                // Full year course
                firstTermIndex = 0;
                lastTermIndex = 7;
            } else if (terms.length() == 4) {
                if (terms.optJSONObject(0).optString("description").equals("1st Six Weeks")) {
                    // First semester course
                    firstTermIndex = 0;
                    lastTermIndex = 3;
                } else {
                    // Second semester course
                    firstTermIndex = 4;
                    lastTermIndex = 7;
                }
            }

            for (int termIndex = firstTermIndex; termIndex <= lastTermIndex; termIndex++) {
                int arrayLocation = termIndex > 3 ? termIndex + 2 : termIndex + 1;
                int average = gradeSummary[classIndex][arrayLocation];
                if (average != NO_GRADES_ENTERED)
                    classList.getJSONObject(jsonIndex).getJSONArray("terms")
                            .getJSONObject(termIndex - firstTermIndex).put("average", average);
            }

            classList.getJSONObject(jsonIndex).put("firstSemesterAverage", gradeSummary[classIndex][5]);
            classList.getJSONObject(jsonIndex).put("secondSemesterAverage", gradeSummary[classIndex][10]);
        }

        // Last updated time of summary --> goes in this awkward place
        classList.getJSONObject(0).put("summaryLastUpdated", new Instant().getMillis());

        return gradeSummary;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.remobile.file.FileUtils.java

public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) {
    if (!configured) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR,
                "File plugin is not configured. Please see the README.md file for details on how to update config.xml"));
        return true;
    }//from   w w w .j ava 2s  .  c  om
    if (action.equals("testSaveLocationExists")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) {
                boolean b = DirectoryManager.testSaveLocationExists();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
            }
        }, args, callbackContext);
    } else if (action.equals("getFreeDiskSpace")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) {
                long l = DirectoryManager.getFreeDiskSpace(false);
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
            }
        }, args, callbackContext);
    } else if (action.equals("testFileExists")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException {
                String fname = args.getString(0);
                boolean b = DirectoryManager.testFileExists(fname);
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
            }
        }, args, callbackContext);
    } else if (action.equals("testDirectoryExists")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException {
                String fname = args.getString(0);
                boolean b = DirectoryManager.testFileExists(fname);
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
            }
        }, args, callbackContext);
    } else if (action.equals("readAsText")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException, MalformedURLException {
                String encoding = args.getString(1);
                int start = args.getInt(2);
                int end = args.getInt(3);
                String fname = args.getString(0);
                readFileAs(fname, start, end, callbackContext, encoding, PluginResult.MESSAGE_TYPE_STRING);
            }
        }, args, callbackContext);
    } else if (action.equals("readAsDataURL")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException, MalformedURLException {
                int start = args.getInt(1);
                int end = args.getInt(2);
                String fname = args.getString(0);
                readFileAs(fname, start, end, callbackContext, null, -1);
            }
        }, args, callbackContext);
    } else if (action.equals("readAsArrayBuffer")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException, MalformedURLException {
                int start = args.getInt(1);
                int end = args.getInt(2);
                String fname = args.getString(0);
                readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_ARRAYBUFFER);
            }
        }, args, callbackContext);
    } else if (action.equals("readAsBinaryString")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException, MalformedURLException {
                int start = args.getInt(1);
                int end = args.getInt(2);
                String fname = args.getString(0);
                readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_BINARYSTRING);
            }
        }, args, callbackContext);
    } else if (action.equals("write")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args)
                    throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
                String fname = args.getString(0);
                String data = args.getString(1);
                int offset = args.getInt(2);
                Boolean isBinary = args.getBoolean(3);
                long fileSize = write(fname, data, offset, isBinary);
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
            }
        }, args, callbackContext);
    } else if (action.equals("truncate")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args)
                    throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
                String fname = args.getString(0);
                int offset = args.getInt(1);
                long fileSize = truncateFile(fname, offset);
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
            }
        }, args, callbackContext);
    } else if (action.equals("requestAllFileSystems")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws IOException, JSONException {
                callbackContext.success(requestAllFileSystems());
            }
        }, args, callbackContext);
    } else if (action.equals("requestAllPaths")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    callbackContext.success(requestAllPaths());
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    } else if (action.equals("requestFileSystem")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws IOException, JSONException {
                int fstype = args.getInt(0);
                long size = args.optLong(1);
                if (size != 0 && size > (DirectoryManager.getFreeDiskSpace(true) * 1024)) {
                    callbackContext.sendPluginResult(
                            new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR));
                } else {
                    JSONObject obj = requestFileSystem(fstype);
                    callbackContext.success(obj);
                }
            }
        }, args, callbackContext);
    } else if (action.equals("resolveLocalFileSystemURI")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws IOException, JSONException {
                String fname = args.getString(0);
                JSONObject obj = resolveLocalFileSystemURI(fname);
                callbackContext.success(obj);
            }
        }, args, callbackContext);
    } else if (action.equals("getFileMetadata")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
                String fname = args.getString(0);
                JSONObject obj = getFileMetadata(fname);
                callbackContext.success(obj);
            }
        }, args, callbackContext);
    } else if (action.equals("getParent")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException, IOException {
                String fname = args.getString(0);
                JSONObject obj = getParent(fname);
                callbackContext.success(obj);
            }
        }, args, callbackContext);
    } else if (action.equals("getDirectory")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException,
                    EncodingException, JSONException {
                String dirname = args.getString(0);
                String path = args.getString(1);
                JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true);
                callbackContext.success(obj);
            }
        }, args, callbackContext);
    } else if (action.equals("getFile")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException,
                    EncodingException, JSONException {
                String dirname = args.getString(0);
                String path = args.getString(1);
                JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false);
                callbackContext.success(obj);
            }
        }, args, callbackContext);
    } else if (action.equals("remove")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException, NoModificationAllowedException,
                    InvalidModificationException, MalformedURLException {
                String fname = args.getString(0);
                boolean success = remove(fname);
                if (success) {
                    callbackContext.success();
                } else {
                    callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
                }
            }
        }, args, callbackContext);
    } else if (action.equals("removeRecursively")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException, FileExistsException, MalformedURLException,
                    NoModificationAllowedException {
                String fname = args.getString(0);
                boolean success = removeRecursively(fname);
                if (success) {
                    callbackContext.success();
                } else {
                    callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
                }
            }
        }, args, callbackContext);
    } else if (action.equals("moveTo")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException,
                    InvalidModificationException, EncodingException, FileExistsException {
                String fname = args.getString(0);
                String newParent = args.getString(1);
                String newName = args.getString(2);
                JSONObject entry = transferTo(fname, newParent, newName, true);
                callbackContext.success(entry);
            }
        }, args, callbackContext);
    } else if (action.equals("copyTo")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException,
                    InvalidModificationException, EncodingException, FileExistsException {
                String fname = args.getString(0);
                String newParent = args.getString(1);
                String newName = args.getString(2);
                JSONObject entry = transferTo(fname, newParent, newName, false);
                callbackContext.success(entry);
            }
        }, args, callbackContext);
    } else if (action.equals("readEntries")) {
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
                String fname = args.getString(0);
                JSONArray entries = readEntries(fname);
                callbackContext.success(entries);
            }
        }, args, callbackContext);
    } else if (action.equals("_getLocalFilesystemPath")) {
        // Internal method for testing: Get the on-disk location of a local filesystem url.
        // [Currently used for testing file-transfer]
        threadhelper(new FileOp() {
            public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
                String localURLstr = args.getString(0);
                String fname = filesystemPathForURL(localURLstr);
                callbackContext.success(fname);
            }
        }, args, callbackContext);
    } else {
        return false;
    }
    return true;
}

From source file:com.phonegap.plugins.discoverscanar.DiscoverScanAR.java

/**
 * Executes the request.// www . jav a  2 s  .  co m
 *
 * This method is called from the WebView thread. To do a non-trivial amount of work, use:
 *     cordova.getThreadPool().execute(runnable);
 *
 * To run on the UI thread, use:
 *     cordova.getActivity().runOnUiThread(runnable);
 *
 * @param action          The action to execute.
 * @param args            The exec() arguments.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return                Whether the action was valid.
 *
 * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java
 */
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    this.callbackContext = callbackContext;

    if (action.equals(ENCODE)) {
        JSONObject obj = args.optJSONObject(0);
        if (obj != null) {
            String type = obj.optString(TYPE);
            String data = obj.optString(DATA);

            // If the type is null then force the type to text
            if (type == null) {
                type = TEXT_TYPE;
            }

            if (data == null) {
                callbackContext.error("User did not specify data to encode");
                return true;
            }

            encode(type, data);
        } else {
            callbackContext.error("User did not specify data to encode");
            return true;
        }
    } else if (action.equals(SCAN)) {

        // Section threading of http://docs.phonegap.com/en/2.3.0/guide_plugin-development_android_index.md.html
        // But it still displayed the error "Plugin should use CordovaInterface.getThreadPool"
        cordova.getThreadPool().execute(new Runnable() {
            //CordovaInterface.getThreadPool().execute(new Runnable() {
            public void run() {
                scan();
            }
        });
    } else if (action.equals(ARSCAN)) {
        JSONObject obj = args.optJSONObject(0);
        // If the type is null then force the type to text
        final String json_file = (obj != null) ? obj.optString(JSONFILE) : null;
        /*
        final String json_file = null;
        if (obj != null) {
        json_file = obj.optString(JSONFILE);
                
        // If the type is null then force the type to text
        }*/
        if (json_file != null) {
            cordova.getThreadPool().execute(new Runnable() {
                //CordovaInterface.getThreadPool().execute(new Runnable() {
                public void run() {
                    arscan(json_file);
                }
            });
        } else {
            callbackContext.error("User did not specify a json file to load");
        }
    } else {
        return false;
    }
    return true;
}

From source file:com.sina.weibo.sdk_lib.openapi.models.PoiList.java

public static PoiList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }//from   w w  w. j av  a 2 s.co  m

    PoiList poiList = new PoiList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);

        poiList.totalNumber = jsonObject.optString("total_number");
        JSONArray jsonArray = jsonObject.optJSONArray("geos");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            poiList.pois = new ArrayList<Poi>(length);
            for (int ix = 0; ix < length; ix++) {
                poiList.pois.add(Poi.parse(jsonArray.optJSONObject(ix)));
            }
        }

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

From source file:com.phelps.liteweibo.model.weibo.Group.java

public static Group parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//w  ww . j a v  a2  s.c om

    Group group = new Group();
    group.user = User.parse(jsonObject.optJSONObject("user"));
    group.id = jsonObject.optString("id");
    group.idStr = jsonObject.optString("idstr");
    group.name = jsonObject.optString("name");
    group.mode = jsonObject.optString("mode");
    group.visible = jsonObject.optInt("visible");
    group.like_count = jsonObject.optInt("like_count");
    group.member_count = jsonObject.optInt("member_count");
    group.description = jsonObject.optString("description");
    group.profile_image_url = jsonObject.optString("profile_image_url");
    group.createAtTime = jsonObject.optString("create_time", "");

    JSONArray jsonArray = jsonObject.optJSONArray("tags");
    if (jsonArray != null && jsonObject.length() > 0) {
        int length = jsonArray.length();
        group.tags = new ArrayList<Tag>(length);
        for (int ix = 0; ix < length; ix++) {
            group.tags.add(Tag.parse(jsonArray.optJSONObject(ix)));
        }
    }

    return group;
}

From source file:koubachi.internal.json.JSONFactory.java

private ArrayList<Device> createDeviceList(JSONArray jsonArray) {
    ArrayList<Device> devices = new ArrayList<Device>();
    for (int i = 0; i < jsonArray.length(); i++)
        devices.add(createDevice(jsonArray.optJSONObject(i)));
    return devices;
}

From source file:koubachi.internal.json.JSONFactory.java

private ArrayList<Plant> createPlantList(JSONArray jsonArray) {
    ArrayList<Plant> plants = new ArrayList<Plant>();
    for (int i = 0; i < jsonArray.length(); i++)
        plants.add(createPlant(jsonArray.optJSONObject(i)));
    return plants;
}

From source file:koubachi.internal.json.JSONFactory.java

private ArrayList<PlantCareAdvice> createPlantCareList(JSONArray jsonArray) {
    ArrayList<PlantCareAdvice> advices = new ArrayList<PlantCareAdvice>();
    for (int i = 0; i < jsonArray.length(); i++)
        advices.add(createCareAdvice(jsonArray.optJSONObject(i)));
    return advices;
}

From source file:koubachi.internal.json.JSONFactory.java

private ArrayList<Sensor> createPlantSensorReadingList(JSONArray jsonArray) {
    ArrayList<Sensor> sensors = new ArrayList<Sensor>();
    for (int i = 0; i < jsonArray.length(); i++)
        sensors.add(createSensor(jsonArray.optJSONObject(i)));
    return sensors;
}

From source file:fr.simon.marquis.secretcodes.util.Utils.java

public static ArrayList<SecretCode> getSecretCodes(Context ctx) {
    ArrayList<SecretCode> res = new ArrayList<SecretCode>();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    try {//from  w ww.  ja va  2  s  . c o  m
        JSONArray array = new JSONArray(prefs.getString(KEY_SECRET_CODES, ""));
        for (int i = 0; i < array.length(); i++) {
            SecretCode code = SecretCode.fromJSON(array.optJSONObject(i));
            if (code != null) {
                res.add(code);
            }
        }
        return res;
    } catch (JSONException e) {
        return res;
    }
}