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:org.michelcity2000.city.stock.ResourceHeap.java

public ResourceHeap(JSONArray jsonResources) {
    int ResourcesNumber = jsonResources.length();
    for (int i = 0; i < ResourcesNumber; i++)
        this.add(Resource.parseResource(jsonResources.getString(i)));
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private Boolean parseMetafile(JSONObject metafile) {
    double version;
    boolean forceVersion;
    boolean allowed = false;
    try {/*from   w w w .  j  av a2 s  .c o m*/
        version = metafile.getDouble("version");
        forceVersion = metafile.getBoolean("forceVersion");
        JSONObject appDetails = metafile.getJSONObject("app");
        JSONArray assets = metafile.getJSONArray("assets");
        JSONArray devices = metafile.getJSONArray("allowedDevices");

        int nAssets = assets.length();
        String packageName = appDetails.getString("packageName");
        int versionCode = appDetails.getInt("versionCode");
        String apkPath = appDetails.getString("APK");
        boolean offlineSupport = appDetails.getBoolean("offlineSupport");

        if (enableDebug) {
            Log.d(TAG, "Version: " + version + ":" + neoUpdateVersion);
            Log.d(TAG, "Package Name: " + packageName + ":" + packageInfo.packageName);
            Log.d(TAG, "APK Path: " + apkPath);
        }

        // Check if it is being updated using offline storage
        if (!offlineSupport && fromOfflineStorage) {
            Log.e(TAG, "Updating from offline storage is disabled for this app?");
            return false;
        }

        db.clearDevicesList();
        for (int i = 0; i < devices.length(); i++) {
            String device = devices.getString(i);
            if (device.length() > 0 && deviceID.compareToIgnoreCase(device) == 0)
                allowed = true;
            db.insertDevice(device);
            if (enableDebug)
                Log.d(TAG, "Device Allowed: " + device);
        }

        // DeviceID or signature error
        if (!allowed)
            return false;

        apkUpdatePath = null;
        if (version > neoUpdateVersion && forceVersion) {
            Log.e(TAG, "neoUpdate seems to be of older version! Required: " + version + " Current: "
                    + neoUpdateVersion);
            return false;
        }

        if (packageInfo.packageName.compareTo(packageName) != 0) {
            Log.e(TAG, "PackageNames don't seem to match - url for some other app? Provided: " + packageName);
            return false;
        }

        if (packageInfo.versionCode < versionCode) {
            // APK Update Required - Lets first do that
            apkUpdatePath = new NewAsset();
            apkUpdatePath.path = apkPath;
            apkUpdatePath.md5 = appDetails.getString("md5");
            return true;
        }

        // Parse the assets
        for (int i = 0; i < nAssets; i++) {
            JSONObject obj = assets.getJSONObject(i);
            NewAsset asset = new NewAsset();
            asset.path = obj.getString("path");
            asset.md5 = obj.getString("md5");

            // Ignore already downloaded files
            if (db.updateAndGetStatus(asset.path, asset.md5) == neoUpdateDB.UPDATE_STATUS.UPDATE_COMPLETE)
                continue;
            filesToDownload.add(asset);
            if (enableDebug) {
                Log.d(TAG, "Enqueued: " + asset.path + " With MD5: " + asset.md5);
            }
        }
        totalFilesToDownload = filesToDownload.size();
    } catch (Exception e) {
        if (enableDebug)
            e.printStackTrace();
        return false;
    }
    return true;
}

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

public void onRestRequestComplete(Methods method, JSONObject result) {
    if (method == Methods.login) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("valid login") == 0) {
                    Auth.loggedIn = true;
                    Auth.Hmac.setCounter(result.getInt("counter"));
                    Auth.Hmac.setIncrement(result.getInt("increment"));
                    PhoneOpenHelper db = new PhoneOpenHelper(this);
                    if (database == null)
                        database = db.getWritableDatabase();
                    API api = new API(this);
                    if (!api.callMethod(Methods.phone, this, (String[]) null)) {
                        Toast msg = Toast.makeText(this, "Error: Calling phone", Toast.LENGTH_LONG);
                        msg.show();/*from   w ww . j  a  v  a2 s .c  o m*/
                    }

                } else if (requestStatus.compareTo("invalid username") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid username", Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("invalid login") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid username and/or password",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("no user") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "No username was provided",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid requestStatus",
                            Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            Toast msg = Toast.makeText(getApplicationContext(),
                    "Could not contact web server.  Please check your connection", Toast.LENGTH_LONG);
            msg.show();
        }
    } else 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();
                    editor.putLong("updateTime", result.getLong("updateTime"));
                    editor.commit();
                    int numbros = result.getInt("numBros");

                    if (numbros > 0) {
                        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);
                        }
                    }
                    Intent homeIntent = new Intent(Login.this, Home.class);
                    Login.this.startActivity(homeIntent);
                    finish();
                } 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) {
                    Toast msg = Toast.makeText(this,
                            "You have been logged out by the server.  Please log in again.", Toast.LENGTH_LONG);
                    msg.show();
                } else {
                    Toast msg = Toast.makeText(this, "Invalid requestStatus", Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {
        Toast msg = Toast.makeText(getApplicationContext(), "Invalid method callback", Toast.LENGTH_LONG);
        msg.show();
    }
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

public void download(final List<String> postID) {
    final DatabaseManager databaseManager = new DatabaseManager(this);

    try {/*from ww  w. j  av a2s.co m*/
        final int num = postID.size() - 1;
        final CountDownLatch latch = new CountDownLatch(num);
        final Executor executor = Executors.newFixedThreadPool(15);

        for (int i = 1; i <= postID.size() - 1; i++) {
            final int count = i;
            final int index = Integer.parseInt(postID.get(i));
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (index != 404) {
                            String url = String.format(POST_URL, index);
                            Request newReq = new Request.Builder().url(url).build();
                            Response newResp = BlogsiteApplication.getInstance().client.newCall(newReq)
                                    .execute();

                            if (!newResp.isSuccessful() && !(newResp.code() == 404)
                                    && !(newResp.code() == 403)) {
                                Log.e("The Jones Theory", "Error: " + newResp.code() + "URL: " + url);
                                LocalBroadcastManager.getInstance(PostDownloader.this)
                                        .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                                throw new IOException();
                            }

                            if (newResp.code() == 404) {
                                return;
                            }

                            String resp = newResp.body().string();

                            JSONObject jObject = new JSONObject(resp);

                            Posts item1 = new Posts();

                            //If the item is not a post break out of loop and ignore it
                            if (!(jObject.optString("type").equals("post"))) {
                                return;
                            }
                            item1.setTitle(jObject.optString("title"));
                            item1.setContent(jObject.optString("content"));
                            item1.setExcerpt(jObject.optString("excerpt"));
                            item1.setPostID(jObject.optInt("ID"));
                            item1.setURL(jObject.optString("URL"));

                            //Parse the Date!
                            String date = jObject.optString("date");
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                            Date newDate = format.parse(date);

                            format = new SimpleDateFormat("yyyy-MM-dd");
                            date = format.format(newDate);

                            item1.setDate(date);

                            //Cuts out all the Child nodes and gets only the  tags.
                            JSONObject Tobj = new JSONObject(jObject.optString("tags"));
                            JSONArray Tarray = Tobj.names();
                            String tagsList = null;

                            if (Tarray != null && (Tarray.length() > 0)) {

                                for (int c = 0; c < Tarray.length(); c++) {
                                    if (tagsList != null) {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = tagsList + ", " + thisTag;
                                    } else {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = thisTag;
                                    }
                                }
                                item1.setTags(tagsList);
                            } else {
                                item1.setTags("");
                            }

                            JSONObject Cobj = new JSONObject(jObject.optString("categories"));
                            JSONArray Carray = Cobj.names();
                            String catsList = null;

                            if (Carray != null && (Carray.length() > 0)) {

                                for (int c = 0; c < Carray.length(); c++) {
                                    if (catsList != null) {
                                        String thisCat = Carray.getString(c);
                                        catsList = catsList + ", " + thisCat;
                                    } else {
                                        String thisCat = Carray.getString(c);
                                        catsList = thisCat;
                                    }
                                }
                                item1.setCategories(catsList);
                            } else {
                                item1.setCategories("");
                            }

                            Integer ImageLength = jObject.optString("featured_image").length();
                            if (ImageLength == 0) {
                                item1.setFeaturedImage(null);
                            } else {
                                item1.setFeaturedImage(jObject.optString("featured_image"));
                            }
                            if (item1 != null) {
                                databaseManager.addPost(item1);
                                Log.d("PostDownloader", index + " database...");
                                double progress = ((double) count / num) * 100;
                                setProgress((int) progress, item1.getTitle(), count);

                                Intent intent = new Intent(DOWNLOAD_PROGRESS);
                                intent.putExtra(PROGRESS, progress);
                                intent.putExtra(NUMBER, num);
                                intent.putExtra(TITLE, item1.getTitle());

                                LocalBroadcastManager.getInstance(PostDownloader.this).sendBroadcast(intent);
                            }
                        }
                    } catch (IOException | JSONException | ParseException e) {
                        if (SharedPrefs.getInstance().isFirstDownload()) {
                            SharedPrefs.getInstance().setFirstDownload(false);
                        }
                        SharedPrefs.getInstance().setDownloading(false);
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            if (SharedPrefs.getInstance().isFirstDownload()) {
                SharedPrefs.getInstance().setFirstDownload(false);
            }
            SharedPrefs.getInstance().setDownloading(false);
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
            mBuilder.setContentText("Download failed.").setSmallIcon(R.drawable.ic_action_file_download)
                    .setAutoCancel(true).setProgress(0, 0, false).setOngoing(false);
            mNotifyManager.notify(NOTIF_ID, mBuilder.build());
            throw new IOException(e);
        }
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);

        Log.d("PostDownloader", "Broadcast Sent!");
        Log.d("The Jones Theory", "download - Downloading = " + SharedPrefs.getInstance().isDownloading());

        Intent mainActIntent = new Intent(this, MainActivity.class);
        PendingIntent clickIntent = PendingIntent.getActivity(this, 57836, mainActIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));
        mBuilder.setContentText("Download complete").setSmallIcon(R.drawable.ic_action_done)
                .setProgress(0, 0, false).setContentIntent(clickIntent).setAutoCancel(true).setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());

    } catch (IOException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setLastRedownladTime(System.currentTimeMillis());
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
        mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true)
                .setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());
    }
}

From source file:robots.ScrapBot.java

public void scrapWeapons(boolean verbose, boolean pretend) throws Exception {
    // TODO: Pretty sure I'll need to ensure that it's scrapping scrappable weapons.  eg. pull out genuines, etc.
    getSchema();//  w  w w.j  ava 2  s.  co  m
    getBackpack();

    final Point smeltWeapons = pointProvider.getPoint(PointPlace.smeltWeapons);

    outputter.output("Scrapping Weapons...");
    leftClick(smeltWeapons.x, smeltWeapons.y);

    // Populate the array with all items and the information we care about.
    int bitmask = 0xFFFF;
    for (int i = 0; i < backpackItems.length(); i++) {
        JSONObject item = backpackItems.getJSONObject(i);
        int inventoryValue = backpackItems.getJSONObject(i).getInt("inventory");
        Weapon currentItem = new Weapon();
        currentItem.setDefindex(item.getInt("defindex"));
        currentItem.setInventorySlot(inventoryValue & bitmask);
        items.add(currentItem);
    }

    // Fill in remaining information and remove non-weapons
    ArrayList<Weapon> newList = new ArrayList<Weapon>();
    for (Weapon item : items) {
        for (int i = 0; i < schemaItems.length(); i++) {
            JSONObject schemaItem = schemaItems.getJSONObject(i);
            if (item.getDefindex().equals(schemaItem.getInt("defindex")) && item.getInventorySlot() > 0) {
                if (schemaItem.has("craft_material_type")) {
                    if (schemaItem.getString("craft_material_type").equals("weapon")) {
                        item.setName(schemaItem.getString("item_name"));
                        JSONArray classesJson = schemaItem.getJSONObject("used_by_classes")
                                .getJSONArray("class");
                        ArrayList<TF2Class> classes = new ArrayList<TF2Class>();
                        for (int j = 0; j < classesJson.length(); j++) {
                            String tf2Class = classesJson.getString(j);
                            TF2Class currentClass = TF2Class.SCOUT;
                            if (tf2Class.equals("Scout"))
                                currentClass = TF2Class.SCOUT;
                            else if (tf2Class.equals("Soldier"))
                                currentClass = TF2Class.SOLIDER;
                            else if (tf2Class.equals("Pyro"))
                                currentClass = TF2Class.PYRO;
                            else if (tf2Class.equals("Demoman"))
                                currentClass = TF2Class.DEMOMAN;
                            else if (tf2Class.equals("Heavy"))
                                currentClass = TF2Class.HEAVY;
                            else if (tf2Class.equals("Engineer"))
                                currentClass = TF2Class.ENGINEER;
                            else if (tf2Class.equals("Medic"))
                                currentClass = TF2Class.MEDIC;
                            else if (tf2Class.equals("Sniper"))
                                currentClass = TF2Class.SNIPER;
                            else if (tf2Class.equals("Spy"))
                                currentClass = TF2Class.SPY;
                            classes.add(currentClass);
                        }
                        item.setClasses(classes);
                        newList.add(item);
                    }
                }
            }
        }
    }
    items = newList;

    // Now, compare and determine two items to scrap
    ArrayList<Weapon> itemsToIgnore = new ArrayList<Weapon>();
    for (Weapon item : items) {
        // If the item is still there, it hasn't been used in crafting OR it hasn't been iterated to yet.
        if (!itemsToIgnore.contains(item)) {
            Weapon match = null;
            for (Weapon hopefulMatch : items) {
                if (!hopefulMatch.equals(item) && !itemsToIgnore.contains(hopefulMatch)) {
                    for (TF2Class tf2Class : item.getClasses()) {
                        for (TF2Class hopefulClass : hopefulMatch.getClasses()) {
                            if (tf2Class.equals(hopefulClass)) {
                                // These two weapons are compatible.  Scrap 'em!
                                match = hopefulMatch;
                                break;
                            }
                        }
                        if (match != null)
                            break;
                    }
                }
                if (match != null)
                    break;
            }
            // Come out here
            if (match != null) {
                // Scrap
                if (verbose)
                    outputter.output("Scrapping a " + item.getName() + " and a " + match.getName() + ".");
                if (!pretend) {
                    scrapWeapons(item, match);
                    Point mouseLoc = MouseInfo.getPointerInfo().getLocation();
                    Point ok2 = pointProvider.getPoint(PointPlace.ok2);
                    if (mouseLoc.getX() != ok2.x || mouseLoc.getY() != ok2.getY())
                        break;
                }
                itemsToIgnore.add(match);
            }
            itemsToIgnore.add(item);
        }
    }
    outputter.output("Weapons Scrapped.");
}

From source file:com.nginious.http.serialize.JsonDeserializer.java

/**
 * Deserializes property with the specified name in the specified json object into a string array.
 * //from  www.  j  ava 2s . c  om
 * @param object the json object
 * @param name the property name
 * @return the deserialized array or <code>null</code> if property doesn't exist
 * @throws SerializerException if unable to deserialize value
 */
protected String[] deserializeStringArray(JSONObject object, String name) throws SerializerException {
    try {
        if (object.has(name)) {
            JSONArray array = object.getJSONArray(name);
            String[] outArray = new String[array.length()];

            for (int i = 0; i < array.length(); i++) {
                outArray[i] = array.getString(i);
            }

            return outArray;
        }

        return null;
    } catch (JSONException e) {
        throw new SerializerException("Can't deserialize string array property " + name, e);
    }
}

From source file:com.quantcast.measurement.service.QCPolicy.java

private boolean parsePolicy(String policyJsonString) {

    boolean successful = true;
    m_blacklist = null;//from  w  w w  .j  av a2s  .co  m
    m_salt = null;
    m_blackoutUntil = 0;
    m_sessionTimeout = null;

    if (!"".equals(policyJsonString)) {
        try {
            JSONObject policyJSON = new JSONObject(policyJsonString);

            if (policyJSON.has(BLACKLIST_KEY)) {
                try {
                    JSONArray blacklistJSON = policyJSON.getJSONArray(BLACKLIST_KEY);
                    if (blacklistJSON.length() > 0) {
                        if (m_blacklist == null) {
                            m_blacklist = new HashSet<String>(blacklistJSON.length());
                        }

                        for (int i = 0; i < blacklistJSON.length(); i++) {
                            m_blacklist.add(blacklistJSON.getString(i));
                        }
                    }
                } catch (JSONException e) {
                    QCLog.w(TAG, "Failed to parse blacklist from JSON.", e);
                }
            }

            if (policyJSON.has(SALT_KEY)) {
                try {
                    m_salt = policyJSON.getString(SALT_KEY);
                    if (USE_NO_SALT.equals(m_salt)) {
                        m_salt = null;
                    }
                } catch (JSONException e) {
                    QCLog.w(TAG, "Failed to parse salt from JSON.", e);
                }
            }

            if (policyJSON.has(BLACKOUT_KEY)) {
                try {
                    m_blackoutUntil = policyJSON.getLong(BLACKOUT_KEY);
                } catch (JSONException e) {
                    QCLog.w(TAG, "Failed to parse blackout from JSON.", e);
                }
            }

            if (policyJSON.has(SESSION_TIMEOUT_KEY)) {
                try {
                    m_sessionTimeout = policyJSON.getLong(SESSION_TIMEOUT_KEY);
                    if (m_sessionTimeout <= 0) {
                        m_sessionTimeout = null;
                    }
                } catch (JSONException e) {
                    QCLog.w(TAG, "Failed to parse session timeout from JSON.", e);
                }
            }
        } catch (JSONException e) {
            QCLog.w(TAG, "Failed to parse JSON from string: " + policyJsonString);
            successful = false;
        }
    }
    return successful;
}

From source file:org.nuxeo.connect.data.PackageDescriptor.java

@JSONImportMethod(name = "conflicts")
protected void setConflictsAsJSON(JSONArray array) throws JSONException {
    PackageDependency[] deps = new PackageDependency[array.length()];
    for (int i = 0; i < array.length(); i++) {
        deps[i] = new PackageDependency(array.getString(i));
    }/*  ww  w. j a va2s  .c  o m*/
    setConflicts(deps);
}

From source file:org.nuxeo.connect.data.PackageDescriptor.java

@JSONImportMethod(name = "dependencies")
protected void setDependenciesAsJSON(JSONArray array) throws JSONException {
    PackageDependency[] deps = new PackageDependency[array.length()];
    for (int i = 0; i < array.length(); i++) {
        deps[i] = new PackageDependency(array.getString(i));
    }/*from  w  w  w.j a  v  a2  s .  c  o m*/
    setDependencies(deps);
}

From source file:org.nuxeo.connect.data.PackageDescriptor.java

/**
 * @since 1.4.26/*  w  w w  .jav  a2  s . com*/
 */
@JSONImportMethod(name = "optionalDependencies")
protected void setOptionalDependenciesAsJSON(JSONArray array) throws JSONException {
    PackageDependency[] deps = new PackageDependency[array.length()];
    for (int i = 0; i < array.length(); i++) {
        deps[i] = new PackageDependency(array.getString(i));
    }
    setOptionalDependencies(deps);
}