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:com.cantwellcode.fitfriend.purchases.Purchase.java

public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    mItemType = itemType;/* w  w  w  . j  a v  a  2s .com*/
    mOriginalJson = jsonPurchaseInfo;
    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:org.catnut.fragment.ConversationFragment.java

@Override
protected void refresh() {
    // ???// w ww . j  a v a2 s  .co  m
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // refresh!
    final int size = getFetchSize();
    (new Thread(new Runnable() {
        @Override
        public void run() {
            // ??????(?-)???Orz...
            String query = CatnutUtils.buildQuery(new String[] { BaseColumns._ID }, null, Comment.TABLE, null,
                    BaseColumns._ID + " desc", size + ", 1" // limit x, y
            );
            Cursor cursor = getActivity().getContentResolver().query(CatnutProvider.parse(Status.MULTIPLE),
                    null, query, null, null);
            // the cursor never null?
            final long since_id;
            if (cursor.moveToNext()) {
                since_id = cursor.getLong(0);
            } else {
                since_id = 0;
            }
            cursor.close();
            final CatnutAPI api = CommentsAPI.to_me(since_id, 0, getFetchSize(), 0, 0, 0);
            // refresh...
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mRequestQueue.add(new CatnutRequest(getActivity(), api,
                            new StatusProcessor.Comments2MeProcessor(), new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d(TAG, "refresh done...");
                                    mTotal = response.optInt(TOTAL_NUMBER);
                                    // ???
                                    JSONArray jsonArray = response.optJSONArray(Comment.MULTIPLE);
                                    int newSize = jsonArray.length(); // ...
                                    Bundle args = new Bundle();
                                    args.putInt(TAG, newSize);
                                    getLoaderManager().restartLoader(0, args, ConversationFragment.this);
                                }
                            }, errorListener)).setTag(TAG);
                }
            });
        }
    })).start();
}

From source file:org.catnut.fragment.ConversationFragment.java

private void loadFromCloud(long max_id) {
    mSwipeRefreshLayout.setRefreshing(true);
    CatnutAPI api = CommentsAPI.to_me(0, max_id, getFetchSize(), 0, 0, 0);
    mRequestQueue.add(new CatnutRequest(getActivity(), api, new StatusProcessor.Comments2MeProcessor(),
            new Response.Listener<JSONObject>() {
                @Override//from   w  w  w  .  j a  va  2 s . c om
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "load more from cloud done...");
                    mTotal = response.optInt(TOTAL_NUMBER);
                    int newSize = response.optJSONArray(Comment.MULTIPLE).length() + mAdapter.getCount();
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, ConversationFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

From source file:com.sudhirkhanger.andpress.rest.WordPressAsyncTask.java

private ArrayList<Post> jsonConvertor(String postJsonStr) {
    ArrayList<Post> postArrayList = new ArrayList<>();

    try {/*from  w w w.  java  2 s .c om*/
        JSONArray baseJsonArray = new JSONArray(postJsonStr);
        int numberOfItems = baseJsonArray.length();

        for (int i = 0; i < numberOfItems; i++) {
            JSONObject item = baseJsonArray.getJSONObject(i);

            int id = item.optInt(ID);

            JSONObject titleObject = item.getJSONObject(TITLE);
            String title = titleObject.optString(RENDERED);

            JSONObject contentObject = item.getJSONObject(CONTENT);
            String content = contentObject.optString(RENDERED);

            String featured_media = item.optString(FEATURED_MEDIA);

            Post post = new Post(id, title, featured_media, content);
            postArrayList.add(post);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Problem parsing the WordPress JSON results", e);
    }
    return postArrayList;
}

From source file:com.basetechnology.s0.agentserver.field.LocationField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !type.equals("date"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    String defaultValue = fieldJson.has("default_value") ? fieldJson.optString("default_value") : null;
    String minValue = fieldJson.has("min_value") ? fieldJson.optString("min_value") : null;
    String maxValue = fieldJson.has("max_value") ? fieldJson.optString("max_value") : null;
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new LocationField(symbolTable, name, label, description, defaultValue, minValue, maxValue,
            nominalWidth, compute);//from w w w  .  ja  va  2s. c  om
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

private void handleCommentsResponse(JSONObject jsonResponse, CommentsListener listener) {

    FbComment comment = null;//from ww  w  .j a  va2  s . co  m
    ArrayList<FbComment> comments = new ArrayList<FbComment>();

    try {
        JSONArray objs = jsonResponse.getJSONArray("data");

        for (int i = 0; i < objs.length(); i++) {
            JSONObject obj = objs.getJSONObject(i);

            comment = new FbComment();
            comment.setId(obj.getString("id"));
            comment.setMessage(obj.optString("message"));
            comment.setCreatedTime(new Date(obj.optLong("created_time") * 1000));
            comment.setNumberOfLikes(obj.optInt("likes"));

            JSONObject fromJson = obj.optJSONObject("from");
            if (fromJson != null) {
                FbSimpleUser fromUser = new FbSimpleUser();
                fromUser.setId(fromJson.getString("id"));
                fromUser.setName(fromJson.optString("name"));

                comment.setFrom(fromUser);
            }

            comments.add(comment);
        }

        String nextPage = null;
        JSONObject paging = jsonResponse.optJSONObject("paging");
        if (paging != null) {
            nextPage = paging.optString("next");
        }

        listener.onComplete(comments, nextPage);

    } catch (JSONException e) {
        Util.logd(TAG, "Could not parse Json response", e);
        listener.onFail(e);
    }
}

From source file:com.andybotting.tramhunter.objects.FavouriteList.java

/**
 * Get the favourite items/*from  w  w  w . ja va 2s  .co m*/
 * @return 
 */
public ArrayList<Favourite> getFavouriteItems() {

    ArrayList<Favourite> favourites = new ArrayList<Favourite>();
    JSONArray favouriteJSONArray = null;
    TramHunterDB db = new TramHunterDB();

    // Fetch JSON favourite stops string from preferences
    String favouriteString = mPreferenceHelper.getStarredStopsString();
    if (LOGV)
        Log.i(TAG, "Parsing favourite string: " + favouriteString);

    // Check to see if we even have any favourites
    if (favouriteString.length() > 1) {

        // Convert any old favourites - if not a JSON Array
        if (!favouriteString.contains("["))
            favouriteString = convertOldFavourites(favouriteString);

        try {
            favouriteJSONArray = new JSONArray(favouriteString);

            for (int i = 0; i < favouriteJSONArray.length(); i++) {

                JSONObject favouriteJSONObject = favouriteJSONArray.getJSONObject(i);

                int tramTrackerID = favouriteJSONObject.optInt("stop");
                int routeID = favouriteJSONObject.optInt("route", -1);
                String name = favouriteJSONObject.optString("name", null);

                Stop stop = db.getStop(tramTrackerID);
                Route route = null;

                if (routeID != -1)
                    route = db.getRoute(routeID);

                favourites.add(new Favourite(stop, route, name));
            }

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

    }
    db.close();
    return favourites;
}

From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java

/**
* 
*///  w  w w .ja v  a 2s .c o m
@Override
protected void onPostExecute(final JSONArray resultList) {
    try {
        if (serverConn.hasError())
            hasError = true;
        else if (resultList != null && resultList.length() > 0) {

            JSONObject resultListItem;

            try {
                resultListItem = resultList.getJSONObject(0);

                /* UUID */

                final String uuid = resultListItem.optString("uuid", "");
                if (uuid != null && uuid.length() != 0)
                    ConfigHelper.setUUID(activity.getApplicationContext(), uuid);

                /* urls */

                final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings();

                final JSONObject urls = resultListItem.optJSONObject("urls");
                if (urls != null) {
                    final Iterator<String> keys = urls.keys();

                    while (keys.hasNext()) {
                        final String key = keys.next();
                        final String value = urls.optString(key, null);
                        if (value != null) {
                            volatileSettings.put("url_" + key, value);
                            if ("statistics".equals(key)) {
                                ConfigHelper.setCachedStatisticsUrl(value, activity);
                            } else if ("control_ipv4_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv4(value, activity);
                            } else if ("control_ipv6_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv6(value, activity);
                            } else if ("url_ipv4_check".equals(key)) {
                                ConfigHelper.setCachedIpv4CheckUrl(value, activity);
                            } else if ("url_ipv6_check".equals(key)) {
                                ConfigHelper.setCachedIpv6CheckUrl(value, activity);
                            }
                        }
                    }
                }

                /* qos names */
                final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc");
                if (qosNames != null) {
                    final Map<String, String> qosNamesMap = new HashMap<String, String>();
                    for (int i = 0; i < qosNames.length(); i++) {
                        JSONObject json = qosNames.getJSONObject(i);
                        qosNamesMap.put(json.optString("test_type"), json.optString("name"));
                    }
                    ConfigHelper.setCachedQoSNames(qosNamesMap, activity);
                }

                /* map server */

                final JSONObject mapServer = resultListItem.optJSONObject("map_server");
                if (mapServer != null) {
                    final String host = mapServer.optString("host");
                    final int port = mapServer.optInt("port");
                    final boolean ssl = mapServer.optBoolean("ssl");
                    if (host != null && port > 0)
                        ConfigHelper.setMapServer(host, port, ssl);
                }

                /* control server version */
                final JSONObject versions = resultListItem.optJSONObject("versions");
                if (versions != null) {
                    if (versions.has("control_server_version")) {
                        ConfigHelper.setControlServerVersion(activity,
                                versions.optString("control_server_version"));
                    }
                }

                // ///////////////////////////////////////////////////////
                // HISTORY / FILTER

                final JSONObject historyObject = resultListItem.getJSONObject("history");

                final JSONArray deviceArray = historyObject.getJSONArray("devices");
                final JSONArray networkArray = historyObject.getJSONArray("networks");

                final String historyDevices[] = new String[deviceArray.length()];

                for (int i = 0; i < deviceArray.length(); i++)
                    historyDevices[i] = deviceArray.getString(i);

                final String historyNetworks[] = new String[networkArray.length()];

                for (int i = 0; i < networkArray.length(); i++)
                    historyNetworks[i] = networkArray.getString(i);

                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                activity.setSettings(historyDevices, historyNetworks);

                activity.setHistoryDirty(true);

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

        } else
            Log.i(DEBUG_TAG, "LEERE LISTE");
    } finally {
        if (endTaskListener != null)
            endTaskListener.taskEnded(resultList);
    }
}

From source file:org.catnut.fragment.TransientUsersFragment.java

private Response<List<TransientUser>> parseNetworkResponse(NetworkResponse response) {
    try {//from   w  ww .  j a  v a2  s.  co m
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        JSONObject result = new JSONObject(jsonString);
        // set next_cursor
        mNext_cursor = result.optInt(User.next_cursor);
        mTotal_number = result.optInt(User.total_number);
        JSONArray array = result.optJSONArray(User.MULTIPLE);
        if (array != null) {
            List<TransientUser> users = new ArrayList<TransientUser>(array.length());
            for (int i = 0; i < array.length(); i++) {
                users.add(TransientUser.convert(array.optJSONObject(i)));
            }
            return Response.success(users, HttpHeaderParser.parseCacheHeaders(response));
        } else {
            throw new RuntimeException("no users found!");
        }
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    } catch (Exception ex) {
        return Response.error(new ParseError(ex));
    }
}

From source file:com.eutectoid.dosomething.picker.PlacePickerFragment.java

@Override
PickerFragmentAdapter createAdapter() {//from  w  w  w .j a  va  2  s. c o  m
    PickerFragmentAdapter adapter = new PickerFragmentAdapter(this.getActivity()) {
        @Override
        protected CharSequence getSubTitleOfGraphObject(JSONObject graphObject) {
            String category = graphObject.optString(CATEGORY);
            int wereHereCount = graphObject.optInt(WERE_HERE_COUNT);

            String result = null;
            if (category != null && wereHereCount != 0) {
                result = getString(R.string.picker_placepicker_subtitle_format, category, wereHereCount);
            } else if (category == null && wereHereCount != 0) {
                result = getString(R.string.picker_placepicker_subtitle_were_here_only_format, wereHereCount);
            } else if (category != null && wereHereCount == 0) {
                result = getString(R.string.picker_placepicker_subtitle_catetory_only_format, category);
            }
            return result;
        }

        @Override
        protected int getGraphObjectRowLayoutId(JSONObject graphObject) {
            return R.layout.picker_placepickerfragment_list_row;
        }

        @Override
        protected int getDefaultPicture() {
            return R.drawable.picker_place_default_icon;
        }

    };
    adapter.setShowCheckbox(false);
    adapter.setShowPicture(getShowPictures());
    return adapter;
}