Example usage for org.json JSONObject optInt

List of usage examples for org.json JSONObject optInt

Introduction

In this page you can find the example usage for org.json JSONObject optInt.

Prototype

public int optInt(String key) 

Source Link

Document

Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number.

Usage

From source file:mc.inappbilling.Purchase.java

public Purchase(String json, String signature) throws JSONException {
    this.json = json;
    JSONObject o = new JSONObject(json);
    this.orderId = o.optString("orderId");
    this.packageName = o.optString("packageName");
    this.sku = o.optString("productId");
    this.purchaseTime = o.optLong("purchaseTime");
    this.purchaseState = o.optInt("purchaseState");
    this.developerPayload = o.optString("developerPayload");
    this.token = o.optString("token", o.optString("purchaseToken"));
    this.signature = signature;
}

From source file:com.vk.sdkweb.api.model.VKApiChat.java

/**
 * Fills a Chat instance from JSONObject.
 *///w ww  .  j a v  a 2 s  .  com
public VKApiChat parse(JSONObject source) {
    id = source.optInt("id");
    type = source.optString("type");
    title = source.optString("title");
    admin_id = source.optInt("admin_id");
    JSONArray users = source.optJSONArray("users");
    if (users != null) {
        this.users = new int[users.length()];
        for (int i = 0; i < this.users.length; i++) {
            this.users[i] = users.optInt(i);
        }
    }
    return this;
}

From source file:uk.co.pilllogger.billing.Purchase.java

public Purchase(String jsonPurchaseInfo, String signature) throws JSONException {
    mOriginalJson = jsonPurchaseInfo;/* w w  w  .  j  av  a2  s.  com*/
    JSONObject o = new JSONObject(mOriginalJson);
    mOrderId = o.optString("orderId");
    mPackageName = o.optString("packageName");
    mSku = o.optString("productId");
    mPurchaseTime = o.optLong("purchaseTime");
    mPurchaseState = o.optInt("purchaseState");
    mDeveloperPayload = o.optString("developerPayload");
    mToken = o.optString("token", o.optString("purchaseToken"));
    mSignature = signature;
}

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

private void getPostAll() {

    //Setup the URLS that I will need
    String firstUrl = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID";
    String nextPage = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID&page_handle=";

    Request request = new Request.Builder().url(firstUrl).build();

    int count = 0;

    try {//from w  w w.ja va  2 s. c o  m

        //First make a call to see how many total posts there are and save to 'found'
        final Response response = BlogsiteApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful()) {
            mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true)
                    .setOngoing(false);
            mNotifyManager.notify(NOTIF_ID, mBuilder.build());
            throw new IOException();
        } else {

            //Take the response and parse the JSON
            JSONObject JObject = new JSONObject(response.body().string());
            JSONArray posts = JObject.optJSONArray("posts");

            //Store the data into the two objects, meta gets the next page later on.
            // Found is total post count.
            String meta = JObject.optString("meta");
            int found = JObject.optInt("found");

            postID = new ArrayList<>();

            //If there are more then 100, which there always will unless something
            // catastrophic happens then set up the newURL.
            if (found > 100) {
                JSONObject metaLink = new JSONObject(meta);
                String nextValue = metaLink.optString("next_page");
                newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
                Log.d("The Jones Theory", newURL);
            }

            // Loop through the posts and add the post ID to the array.
            // The posts is still from the original call.
            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                postID.add(post.optString("ID"));
                count++;
            }

            //Now this logic is in charge of loading the next pages
            // until all posts are loaded into the array.
            while (count != found) {
                Request newRequest = new Request.Builder().url(newURL).build();
                Response newResponse = BlogsiteApplication.getInstance().client.newCall(newRequest).execute();
                if (!newResponse.isSuccessful())
                    throw new IOException();

                JSONObject nJObject = new JSONObject(newResponse.body().string());
                JSONArray nPosts = nJObject.optJSONArray("posts");
                String nMeta = nJObject.optString("meta");
                int newFound = nJObject.optInt("found");

                if (newFound > 100) {
                    JSONObject metaLink = new JSONObject(nMeta);
                    String nextValue = metaLink.optString("next_page");
                    newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
                }
                for (int i = 0; i < nPosts.length(); i++) {
                    JSONObject post = nPosts.optJSONObject(i);
                    postID.add(post.optString("ID"));
                    count++;
                }
            }
            Collections.reverse(postID);
            download(postID);
            Log.d("The Jones Theory",
                    "getPostAll - Downloading = " + SharedPrefs.getInstance().isDownloading());
        }
    } catch (IOException | JSONException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
    }
}

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

private void getPostMissing() {
    notificationService();//from  w w  w  .  ja v a 2s . com
    SharedPrefs.getInstance().setDownloading(true);
    DatabaseManager databaseManager = new DatabaseManager(this);
    //Setup the URLS that I will need
    String firstUrl = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID";
    String nextPage = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID&page_handle=";
    Request request = new Request.Builder().url(firstUrl).build();
    int count = 0;

    try {

        //First make a call to see how many total posts there are and save to 'found'
        final Response response = BlogsiteApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException();

        //Take the response and parse the JSON
        JSONObject JObject = new JSONObject(response.body().string());
        JSONArray posts = JObject.optJSONArray("posts");

        //Store the data into the two objects, meta gets the next page later on.
        // Found is total post count.
        String meta = JObject.optString("meta");
        int found = JObject.optInt("found");

        postID = new ArrayList<>();

        //If there are more then 100, which there always will unless something
        // catastrophic happens then set up the newURL.
        if (found > 100) {
            JSONObject metaLink = new JSONObject(meta);
            String nextValue = metaLink.optString("next_page");
            newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
        }

        // Loop through the posts and add the post ID to the array.
        // The posts is still from the original call.
        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);
            if (!databaseManager.idExists(post.optString("ID"))) {
                postID.add(post.optString("ID"));
            }
            count++;
        }

        //Now this logic is in charge of loading the next pages
        // until all posts are loaded into the array.
        while (count != found) {
            Request newRequest = new Request.Builder().url(newURL).build();
            Response newResponse = BlogsiteApplication.getInstance().client.newCall(newRequest).execute();
            if (!newResponse.isSuccessful())
                throw new IOException();

            JSONObject nJObject = new JSONObject(newResponse.body().string());
            JSONArray nPosts = nJObject.optJSONArray("posts");
            String nMeta = nJObject.optString("meta");
            int newFound = nJObject.optInt("found");

            if (newFound > 100) {
                JSONObject metaLink = new JSONObject(nMeta);
                String nextValue = metaLink.optString("next_page");
                newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");

            }

            for (int i = 0; i < nPosts.length(); i++) {
                JSONObject post = nPosts.optJSONObject(i);
                if (!databaseManager.idExists(post.optString("ID"))) {
                    postID.add(post.optString("ID"));
                }
                count++;
            }
        }
    } catch (IOException | JSONException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
    }
    Collections.reverse(postID);
    download(postID);
}

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

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

    try {//ww  w. jav a2 s . com
        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:com.bt.heliniumstudentapp.UpdateClass.java

@Override
protected void onPostExecute(String html) {
    if (html != null) {
        try {//from  w  ww.  ja  v  a 2  s .  c o m
            final JSONObject json = (JSONObject) new JSONTokener(html).nextValue();

            versionName = json.optString("version_name");
            final int versionCode = json.optInt("version_code");

            try {
                final int currentVersionCode = context.getPackageManager()
                        .getPackageInfo(context.getPackageName(), 0).versionCode;

                if (versionCode > currentVersionCode) {
                    if (!settings)
                        updateDialog.show();

                    updateDialog.setTitle(context.getString(R.string.update) + ' ' + versionName);

                    final TextView contentTV = (TextView) updateDialog.findViewById(R.id.tv_content_du);
                    contentTV.setTextColor(ContextCompat.getColor(context, MainActivity.themePrimaryTextColor));
                    contentTV.setText(Html.fromHtml(json.optString("content"), null, new Html.TagHandler() {

                        @Override
                        public void handleTag(boolean opening, String tag, Editable output,
                                XMLReader xmlReader) {
                            if ("li".equals(tag))
                                if (opening)
                                    output.append(" \u2022 ");
                                else
                                    output.append("\n");
                        }
                    }));

                    updateDialog.setCanceledOnTouchOutside(true);

                    updateDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);

                    updateDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                            .setTextColor(ContextCompat.getColor(context, MainActivity.accentSecondaryColor));
                } else if (settings) {
                    updateDialog.setTitle(context.getString(R.string.update_no));

                    final TextView contentTV = (TextView) updateDialog.findViewById(R.id.tv_content_du);
                    contentTV.setTextColor(ContextCompat.getColor(context, MainActivity.themePrimaryTextColor));
                    contentTV.setText(Html.fromHtml(json.optString("content"), null, new Html.TagHandler() {

                        @Override
                        public void handleTag(boolean opening, String tag, Editable output,
                                XMLReader xmlReader) {
                            if ("li".equals(tag))
                                if (opening)
                                    output.append(" \u2022 ");
                                else
                                    output.append("\n");
                        }
                    }));

                    updateDialog.setCanceledOnTouchOutside(true);
                }
            } catch (NameNotFoundException e) {
                Toast.makeText(context, R.string.error, Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            Toast.makeText(context, R.string.error, Toast.LENGTH_SHORT).show();
        }
    } else if (settings) {
        updateDialog.cancel();

        final AlertDialog.Builder updateDialogBuilder = new AlertDialog.Builder(
                new ContextThemeWrapper(context, MainActivity.themeDialog));

        updateDialogBuilder.setTitle(context.getString(R.string.update));

        updateDialogBuilder.setMessage(R.string.error_update);

        updateDialogBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                downloadAPK();
            }
        });

        updateDialogBuilder.setNegativeButton(android.R.string.no, null);

        final AlertDialog updateDialog = updateDialogBuilder.create();

        updateDialog.setCanceledOnTouchOutside(true);
        updateDialog.show();

        updateDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                .setTextColor(ContextCompat.getColor(context, MainActivity.accentSecondaryColor));
        updateDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                .setTextColor(ContextCompat.getColor(context, MainActivity.accentSecondaryColor));
    }
}

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

public static GroupList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }/*from  w  w  w.j a  va2 s  .  c  o m*/

    GroupList groupList = new GroupList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        groupList.total_number = jsonObject.optInt("total_number");

        JSONArray jsonArray = jsonObject.optJSONArray("lists");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            groupList.groupList = new ArrayList<Group>(length);
            for (int ix = 0; ix < length; ix++) {
                groupList.groupList.add(Group.parse(jsonArray.optJSONObject(ix)));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return groupList;
}

From source file:com.trellmor.berrytube.ChatMessage.java

/**
 * Constructs a <code>ChatMessage</code> from an <code>JSONObject</code>
 * /*from   ww  w. ja  va  2s. c  om*/
 * @param message
 *            <code>JSONObject<code> containing all the required fields to form a chat message
 * @throws JSONException
 */
public ChatMessage(JSONObject message) throws JSONException {
    mNick = message.getString("nick");
    mMsg = message.getString("msg");
    mMulti = message.getInt("multi");
    mType = message.getInt("type");

    // check emote
    if (message.has("emote") && message.get("emote") instanceof String) {
        String emote = message.getString("emote");
        if (emote.compareTo("rcv") == 0)
            this.mEmote = EMOTE_RCV;
        else if (emote.compareTo("sweetiebot") == 0)
            this.mEmote = EMOTE_SWEETIEBOT;
        else if (emote.compareTo("spoiler") == 0)
            this.mEmote = EMOTE_SPOILER;
        else if (emote.compareTo("act") == 0)
            this.mEmote = EMOTE_ACT;
        else if (emote.compareTo("request") == 0)
            this.mEmote = EMOTE_REQUEST;
        else if (emote.compareTo("poll") == 0)
            this.mEmote = EMOTE_POLL;
        else if (emote.compareTo("drink") == 0)
            this.mEmote = EMOTE_DRINK;
    } else
        mEmote = 0;

    JSONObject metadata = message.getJSONObject("metadata");
    mFlair = metadata.optInt("flair");
    mFlaunt = metadata.optBoolean("nameflaunt");

    try {
        this.mTimeStamp = TIMESTAMP_FORMAT.parse(message.getString("timestamp")).getTime();
    } catch (ParseException pe) {
        Log.w(TAG, "Error parsing timestamp string");
        this.mTimeStamp = System.currentTimeMillis();
    }
    this.mHidden = (this.mEmote == EMOTE_SPOILER);
}

From source file:com.bojie.weatherbo.ui.inappbilling.Purchase.java

public Purchase(final String itemType, final String jsonPurchaseInfo, final String signature)
        throws JSONException {
    mItemType = itemType;/*from   w  w  w . j av a2s  .  com*/
    mOriginalJson = jsonPurchaseInfo;
    final JSONObject o = new JSONObject(mOriginalJson);
    mOrderId = o.optString("orderId");
    mPackageName = o.optString("packageName");
    mSku = o.optString("productId");
    mPurchaseTime = o.optLong("purchaseTime");
    mPurchaseState = o.optInt("purchaseState");
    mDeveloperPayload = o.optString("developerPayload");
    mToken = o.optString("token", o.optString("purchaseToken"));
    mSignature = signature;
}