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.ymt.demo1.plates.hub.MyHubFragment.java

/**
 * ?/*from  w  w  w . j  a va  2 s.c o m*/
 */
protected StringRequest getHubSysInfo(String userName) {
    return new StringRequest(BaseURLUtil.getHubSysInfo(userName), new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                if (jsonObject.getInt("retCode") == 0) {
                    JSONArray array = jsonObject.getJSONArray("data");
                    int length = array.length();
                    for (int i = 0; i < length; i++) {
                        JSONObject object = array.getJSONObject(i);
                        MyHubSysInfo sysInfo = new MyHubSysInfo();
                        sysInfo.setAuthor(object.optInt("author"));
                        sysInfo.setAuthorid(object.optInt("authorid"));
                        sysInfo.setCategory(object.optInt("category"));
                        sysInfo.setDateline(object.optInt("dateline"));
                        sysInfo.setFrom_id(object.optInt("from_id"));
                        sysInfo.setFrom_idtype(object.optString("from_idtype"));
                        sysInfo.setFrom_num(object.optInt("from_num"));
                        sysInfo.setThe_id(object.optInt("id"));
                        sysInfo.setNew_(object.optInt("new_"));
                        sysInfo.setNote(object.optString("note"));
                        sysInfo.setType(object.optString("type"));
                        sysInfo.setUid(object.optInt("uid"));
                        sysInfoList.add(sysInfo);

                    }
                    hubSysInfoAdapter.setSubjects(sysInfoList);
                }
            } catch (JSONException e) {
                AppContext.toastBadJson();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            AppContext.toastBadInternet();
        }
    });
}

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

/**
 * Fills a Place instance from JSONObject.
 *///from  ww  w  .j  a  va  2s .c  o  m
public VKApiPlace parse(JSONObject from) {
    id = from.optInt("id");
    title = from.optString("title");
    latitude = from.optDouble("latitude");
    longitude = from.optDouble("longitude");
    created = from.optLong("created");
    checkins = from.optInt("checkins");
    updated = from.optLong("updated");
    country_id = from.optInt("country");
    city_id = from.optInt("city");
    address = from.optString("address");
    return this;
}

From source file:com.example.SmartBoard.DrawingView.java

@Override
protected void onDraw(Canvas canvas) {

    drawCanvas.drawPath(drawPath, drawPaint);
    drawCanvas.drawPath(drawPathRecv, drawPaintSender);

    if (rectMode) {
        //draw rectangle
        drawPaint.setXfermode(null);//from ww w. j  av  a  2 s  .  c  o m
        onDrawRectangle(canvas);
    } else if (circleMode) {
        drawPaint.setXfermode(null);
        onDrawCircle(canvas);
    } else if (lineMode) {
        drawPaint.setXfermode(null);
        onDrawLine(canvas);
    } else if (textMode) {
        drawPaint.setXfermode(null);
        onDrawText(canvas);
    } else if (dragMode && !dragFinished) {
        drawPaint.setXfermode(null);
        onDragDraw(canvas, dragX, dragY);
    } else if (colorDropperMode) {
        drawPaint.setXfermode(null);
        onDrawColorDropper(canvas, dropperX, dropperY);
    } else if (textSizeMode) {
        drawPaint.setXfermode(null);
    }

    canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);

    //redraw objects

    Paint tempPaint = new Paint();
    tempPaint.setStyle(Paint.Style.STROKE);

    for (String key : textObjects.keySet()) {
        if (key.compareTo("") == 0) {
            continue;
        }
        JSONObject o = textObjects.get(key);

        tempPaint.setColor(o.optInt("color"));
        tempPaint.setStrokeWidth(o.optInt("size"));

        canvas.drawBitmap(mqtt.stringToBitmap(o.optString("textBitmap")), o.optInt("x"), o.optInt("y"),
                tempPaint);

    }

    for (String key : objectDrawables.keySet()) {
        //hashtable problems no time to explain. But it creates a duplicate of last item I add to the table.
        //So dont print duplicates which have empty string key values
        if (key.compareTo("") == 0) {
            continue;
        }
        JSONObject o = objectDrawables.get(key);

        String objectType = o.optString("type");
        tempPaint.setColor(o.optInt("color"));
        tempPaint.setStrokeWidth(o.optInt("size"));

        if (objectType.compareTo("Circle") == 0) {
            canvas.drawCircle(o.optInt("x"), o.optInt("y"), o.optInt("radius"), tempPaint);

        } else if (objectType.compareTo("Line") == 0) {
            canvas.drawLine(o.optInt("startx"), o.optInt("starty"), o.optInt("stopx"), o.optInt("stopy"),
                    tempPaint);

        } else if (objectType.compareTo("Rectangle") == 0) {
            canvas.drawRect(Rect.unflattenFromString(o.optString("dimens")), tempPaint);
        } else if (objectType.compareTo("Text") == 0) {
            //canvas.drawRect(Rect.unflattenFromString(o.optString("region")), drawPaint);
            canvas.drawBitmap(mqtt.stringToBitmap(o.optString("textBitmap")), o.optInt("x"), o.optInt("y"),
                    tempPaint);

        }
    }

}

From source file:com.example.SmartBoard.DrawingView.java

/***********************************************************************************/
//handles color dropper mode touch events
public void onTouchColorDropperMode(MotionEvent event) {

    int X = (int) event.getX();
    int Y = (int) event.getY();
    dropperX = X;/*from  ww  w  . jav a2  s .  c o  m*/
    dropperY = Y;

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        JSONObject touchedObject = getTouchedObject(X, Y);
        if (touchedObject != null) {

            try {
                touchedObject.put("color", dropperColor);
                //for text
                if (touchedObject.optString("type").compareTo("Text") == 0) {
                    Bitmap bm = textToBitmap(touchedObject.optString("text"), dropperColor,
                            touchedObject.optInt("x"), touchedObject.optInt("y"), touchedObject.optInt("size"));
                    touchedObject.put("textBitmap", mqtt.bitmapToString(bm));
                }
                mqtt.publishObject(touchedObject);
            } catch (JSONException e) {

            }
            invalidate();
        }
    }

}

From source file:com.example.SmartBoard.DrawingView.java

public void onTouchTextResizeEvent(MotionEvent event) {
    int eventaction = event.getAction();

    int X = (int) event.getX();
    int Y = (int) event.getY();
    textResizePosX = X;/* w  w  w.j  ava2 s.c om*/
    textResizePosY = Y;

    JSONObject touchedObject = getTouchedObject(X, Y);
    if (touchedObject != null) {

        try {

            //for text
            if (touchedObject.optString("type").compareTo("Text") == 0) {
                touchedObject.put("size", textViewSize);
                Bitmap bm = textToBitmap(touchedObject.optString("text"), touchedObject.optInt("color"),
                        touchedObject.optInt("x"), touchedObject.optInt("y"), textViewSize);
                touchedObject.put("textBitmap", mqtt.bitmapToString(bm));
            }
            mqtt.publishObject(touchedObject);
        } catch (JSONException e) {

        }
        invalidate();
    }
}

From source file:com.example.SmartBoard.DrawingView.java

public boolean onTouchDragEvent(MotionEvent event) {

    boolean handled = false;

    JSONObject mObjectTouched;
    int X;/* w  w w .ja v  a  2  s.  com*/
    int Y;
    int pointerId;
    int actionIndex = event.getActionIndex();

    //get coordinates and make object transparent
    switch (event.getActionMasked()) {
    case MotionEvent.ACTION_DOWN:
        dragFinished = false;

        //it's the first pointer, so clear all existing pointers data
        mObjectPointers.clear();
        X = (int) event.getX(actionIndex);
        Y = (int) event.getY(actionIndex);
        dragX = X;
        dragY = Y;
        String objectType = "";
        //check if we've touched inside some object
        mObjectTouched = getTouchedObject(X, Y);

        if (mObjectTouched == null) {
            return true;
        } else {
            objectType = getObjectType(mObjectTouched);
        }

        if (objectType.compareTo("Circle") == 0) {
            try {
                mObjectTouched.put("x", X);
                mObjectTouched.put("y", Y);

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

            }
        } else if (objectType.compareTo("Rectangle") == 0) {
            Rect tempRect = Rect.unflattenFromString(mObjectTouched.optString("dimens"));
            tempRect.set(X, Y, X + tempRect.width(), Y + tempRect.height());
            try {
                mObjectTouched.put("dimens", tempRect.flattenToString());
            } catch (JSONException e) {

            }

        } else if (objectType.compareTo("Line") == 0) {

            if (lengthOfLine(X, Y, mObjectTouched.optInt("startx"),
                    mObjectTouched.optInt("starty")) < lengthOfLine(X, Y, mObjectTouched.optInt("stopx"),
                            mObjectTouched.optInt("stopy"))) {

                try {
                    mObjectTouched.put("startx", X);
                    mObjectTouched.put("starty", Y);
                    mObjectTouched.put("length",
                            lengthOfLine(X, Y, mObjectTouched.optInt("stopx"), mObjectTouched.optInt("stopy")));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dragLineStart = true;
            } else {
                try {
                    mObjectTouched.put("stopx", X);
                    mObjectTouched.put("stopy", Y);
                    mObjectTouched.put("length", lengthOfLine(X, Y, mObjectTouched.optInt("startx"),
                            mObjectTouched.optInt("starty")));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dragLineStart = false;
            }

        } else if (objectType.compareTo("Text") == 0) {
            try {
                mObjectTouched.put("x", X);
                mObjectTouched.put("y", Y);
                Rect tempRect = Rect.unflattenFromString(mObjectTouched.getString("region"));
                tempRect.set(X, Y, tempRect.width() + X, tempRect.height() + Y);
                mObjectTouched.put("region", tempRect.flattenToString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        mObjectPointers.put(event.getPointerId(0), mObjectTouched);
        if (mObjectTouched != null) {
            mqtt.publishObject(mObjectTouched);
        }
        invalidate();
        handled = true;
        break;

    case MotionEvent.ACTION_POINTER_DOWN:
        break;
    case MotionEvent.ACTION_MOVE:
        dragFinished = false;

        final int pointerCount = event.getPointerCount();

        for (actionIndex = 0; actionIndex < pointerCount; actionIndex++) {
            //some pointer has moved, search it by pointer id
            pointerId = event.getPointerId(actionIndex);
            X = (int) event.getX(actionIndex);
            Y = (int) event.getY(actionIndex);

            dragX = X;
            dragY = Y;

            mObjectTouched = mObjectPointers.get(pointerId);
            if (mObjectTouched == null)
                continue; // if null no object was touched so skip

            if (mObjectTouched.optString("type").compareTo("Circle") == 0) {
                try {
                    mObjectTouched.put("x", X);
                    mObjectTouched.put("y", Y);
                } catch (JSONException e) {
                }
            } else if (mObjectTouched.optString("type").compareTo("Rectangle") == 0) {

                Rect tempRect = Rect.unflattenFromString(mObjectTouched.optString("dimens"));
                tempRect.set(X, Y, X + tempRect.width(), Y + tempRect.height());
                try {
                    mObjectTouched.put("dimens", tempRect.flattenToString());
                } catch (JSONException e) {

                }

            } else if (mObjectTouched.optString("type").compareTo("Text") == 0) {
                try {
                    mObjectTouched.put("x", X);
                    mObjectTouched.put("y", Y);
                    Rect tempRect = Rect.unflattenFromString(mObjectTouched.getString("region"));
                    tempRect.set(X, Y, tempRect.width() + X, tempRect.height() + Y);
                    mObjectTouched.put("region", tempRect.flattenToString());
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }

            else if (mObjectTouched.optString("type").compareTo("Line") == 0) {

                if (dragLineStart) {
                    try {
                        mObjectTouched.put("startx", X);
                        mObjectTouched.put("starty", Y);
                        mObjectTouched.put("length", lengthOfLine(X, Y, mObjectTouched.optInt("stopx"),
                                mObjectTouched.optInt("stopy")));

                        //mObjectTouched.put("stopx", tempStopX);
                        // mObjectTouched.put("stopy", tempStopY);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        mObjectTouched.put("stopx", X);
                        mObjectTouched.put("stopy", Y);
                        mObjectTouched.put("length", lengthOfLine(X, Y, mObjectTouched.optInt("startx"),
                                mObjectTouched.optInt("starty")));

                        //mObjectTouched.put("stopx", tempStopX);
                        // mObjectTouched.put("stopy", tempStopY);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }

            if (mObjectTouched != null) {
                mqtt.publishObject(mObjectTouched);
            }
        }

        invalidate();
        handled = true;
        break;
    case MotionEvent.ACTION_UP:
        dragFinished = true;

        mObjectPointers.clear();
        invalidate();
        handled = true;
        break;
    case MotionEvent.ACTION_CANCEL:
        handled = true;
        break;

    default:
        // do nothing
        break;
    }

    return super.onTouchEvent(event) || handled;
}

From source file:com.example.SmartBoard.DrawingView.java

private JSONObject getTouchedObject(final int xTouch, final int yTouch) {
    JSONObject touched = null;//ww w. j a  v  a  2  s  .  c  o  m

    //makes textObjects preferable on selection for drag
    //search for text object first
    for (JSONObject textObject : textObjects.values()) {
        Rect region = Rect.unflattenFromString(textObject.optString("region"));
        //System.out.println(region);
        if (region.contains(xTouch, yTouch)) {

            touched = textObject;
            return touched;
        }
    }

    for (JSONObject object : objectDrawables.values()) {

        if (object.optString("type").compareTo("Circle") == 0) {
            int x = object.optInt("x");
            int y = object.optInt("y");
            int radius = object.optInt("radius");

            if ((x - xTouch) * (x - xTouch) + (y - yTouch) * (y - yTouch) <= radius * radius) {
                touched = object;
                break;
            }
        } else if (object.optString("type").compareTo("Rectangle") == 0) {
            Rect tempRect = Rect.unflattenFromString(object.optString("dimens"));
            if (tempRect.contains(xTouch, yTouch)) {
                touched = object;
                break;
            }
        } else if (object.optString("type").compareTo("Line") == 0) {

            double tempGradient = gradient(object.optInt("startx"), object.optInt("starty"), xTouch, yTouch);
            int startx = object.optInt("startx");
            int stopx = object.optInt("stopx");
            int starty = object.optInt("starty");
            int stopy = object.optInt("stopy");

            if (lengthOfLine(startx, starty, xTouch, yTouch)
                    + lengthOfLine(stopx, stopy, xTouch, yTouch) <= object.optDouble("length") + 5) {
                touched = object;
                break;
            }

        } else if (object.optString("type").compareTo("Text") == 0) {

            Rect region = Rect.unflattenFromString(object.optString("region"));
            //System.out.println(region);
            if (region.contains(xTouch, yTouch)) {

                touched = object;
                break;
            }
        }
    }

    return touched;
}

From source file:de.robbers.dashclock.stackextension.StackExtension.java

private void parseReputationResponse(String json) {
    if (json == null) {
        return;/*from www. jav  a 2 s  . c om*/
    }
    mExpandedBody = "";
    LongSparseArray reputationArray = new LongSparseArray();
    try {
        JSONArray items = new JSONObject(json).getJSONArray("items");
        Log.i(TAG, items.toString(2));

        for (int i = 0; i < items.length(); i++) {
            JSONObject reputation = items.getJSONObject(i);
            long postId = reputation.optLong("post_id");
            int reputationChange = reputation.optInt("reputation_change");
            int newValue = reputationChange;
            newValue += (Integer) reputationArray.get(postId, 0);
            reputationArray.put(postId, newValue);
        }

        List<Long> postIds = new ArrayList<Long>();
        for (int i = 0; i < items.length(); i++) {
            JSONObject reputation = items.getJSONObject(i);
            long postId = reputation.optLong("post_id");
            int reputationChange = reputation.optInt("reputation_change");
            if (postIds.contains(postId) || reputationChange == 0) {
                continue;
            }
            postIds.add(postId);
            int reputationValue = (Integer) reputationArray.get(postId);
            String title = String.valueOf(Html.fromHtml(reputation.optString("title")));
            mExpandedBody += buildExpandedBodyPost(reputationValue, title, postIds.size());
        }
    } catch (JSONException e) {
        Log.i(TAG, json);
        e.printStackTrace();
    }
    if (TextUtils.isEmpty(mExpandedBody)) {
        mExpandedBody = getString(R.string.no_recent_reputation_changes);
    }
}

From source file:com.orange.labs.sdk.session.AuthSession.java

@Override
public void refresh(final OrangeListener.Success<String> success, final OrangeListener.Error failure) {

    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(context);

    // Prepare URL
    String url = API_SERVER + "/oauth/v2/token";

    // Prepare params in body request
    JSONObject params = new JSONObject();
    try {//from   w ww.ja  v a  2 s  . co  m
        params.put("grant_type", "refresh_token");
        params.put("refresh_token", getRefreshToken());
        params.put("scope", getScope());
        params.put("redirect_uri", getRedirectUri());

        getRestClient().jsonRequest("/session/refresh/", Request.Method.POST, url, params, getHeaders(),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        accessToken = response.optString("access_token");
                        setExpiresIn(response.optInt("expires_in"));
                        success.onResponse("OK");
                    }
                }, failure);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.orange.labs.sdk.session.AuthSession.java

/**
 * Check if authentication is successfull.
 * @param success/*from w  w  w .  j a  va2s  .c o m*/
 * @param failure
 */
public void checkAuthentication(final OrangeListener.Success<String> success,
        final OrangeListener.Error failure) {

    String refreshToken = getRefreshToken();
    // Check Refresh Token
    if (refreshToken == null || refreshToken.length() == 0) {
        // Check the result of AuthActivity

        // Check if an error occurred
        Intent data = AuthActivity.result;
        if (data != null) {
            Bundle extras = data.getExtras();
            OrangeAPIException exception = (OrangeAPIException) extras
                    .getSerializable(AuthActivity.EXTRA_EXCEPTION_ERROR);

            if (exception != null) {

                failure.onErrorResponse(exception);
            } else {
                // Check the authorization code to return an access token, refresh token...

                // Prepare URL
                String url = API_SERVER + "/oauth/v2/token";
                // Prepare params in body request
                JSONObject params = new JSONObject();
                try {
                    params.put("grant_type", "authorization_code");
                    params.put("code", data.getStringExtra(AuthActivity.EXTRA_AUTHORIZATION_CODE));
                    params.put("redirect_uri", redirectURI);

                    getRestClient().jsonRequest("/session/check/authorizationCode", Request.Method.POST, url,
                            params, getHeaders(), new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    // save values :
                                    accessToken = response.optString("access_token");

                                    setExpiresIn(response.optInt("expires_in"));

                                    setRefreshToken(response.optString("refresh_token"));

                                    // Check that authent is success !
                                    SharedPreferences sharedPref = context
                                            .getSharedPreferences(SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
                                    SharedPreferences.Editor editor = sharedPref.edit();
                                    editor.putBoolean(SHARED_PREFERENCES_FORCE_LOGIN, false);
                                    editor.commit();

                                    success.onResponse("OK");
                                }
                            }, failure);

                } catch (JSONException e) {
                    failure.onErrorResponse(new OrangeAPIException());
                }
            }
        }
    } else {
        // get the access token with refresh token
        refresh(success, failure);
    }
}