Example usage for org.json JSONObject optDouble

List of usage examples for org.json JSONObject optDouble

Introduction

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

Prototype

public double optDouble(String key) 

Source Link

Document

Get an optional double associated with a key, or NaN if there is no such key or if its value is not a number.

Usage

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

public void messageArrived(String topic, MqttMessage message) {
    MyActivity drawingActivity = (MyActivity) drawingContext;
    JSONObject recvMessage = null;

    if (message.toString().compareTo("") == 0) {
        //user went offline
        String[] topicStruct = topic.split("/");
        // System.out.println("user to be removed: "+topicStruct[2]);

        if (topicStruct[2].compareTo("users") == 0) {
            usersListHistory.remove(new OnlineStateMessage(null, topicStruct[3]));
            usersAdapter.notifyDataSetChanged();

        } else if (topicStruct[2].compareTo("objects") == 0) {
            drawingActivity.drawer.removeObject(topicStruct[3]);
        }//from  w  w  w  . j a  v  a2  s  . c om
        return;
    }

    try {
        recvMessage = new JSONObject(message.toString());
    } catch (JSONException j) {
        j.printStackTrace();
    }

    if (recvMessage.optString("status").compareTo("online") == 0) {

        OnlineStateMessage newUser = new OnlineStateMessage(recvMessage.optString("selfie"),
                recvMessage.optString("userId"));
        // System.out.println("user added: "+ recvMessage.optString("userId"));
        usersListHistory.add(newUser);
        usersAdapter.notifyDataSetChanged();
        return;

    }

    String clientId = recvMessage.optString("clientId");

    if (clientId.compareTo(client.getClientId()) != 0) {

        switch (type.valueOf(recvMessage.optString("type"))) {

        case Point:
            drawingActivity.drawer.drawPoint((float) recvMessage.optDouble("mX"),
                    (float) recvMessage.optDouble("mY"), recvMessage.optInt("drawActionFlag"),
                    recvMessage.optInt("color"), recvMessage.optString("mode"), recvMessage.optInt("brushSize"),
                    recvMessage.optString("clientId"));
            break;
        case Eraser:
            float eSize = (float) recvMessage.optDouble("size");
            drawingActivity.drawer.updateEraseSize(eSize);
            break;
        case Pencil: //shares topic with Eraser
            float size = (float) recvMessage.optDouble("size");
            drawingActivity.drawer.updateBrushSize(size);
            break;

        case ColorChange:
            drawingActivity.drawer.updateColor(recvMessage.optInt("code"));
            break;

        case ClearScreen:
            drawingActivity.drawer.updateClearScreen();
            break;
        case Chat:
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(new long[] { 3, 100 }, -1);

            String[] nameMessage = recvMessage.optString("message").split(":");
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
                    .setLargeIcon(stringToBitmap(recvMessage.optString("selfie")))
                    .setSmallIcon(R.drawable.smart2).setContentTitle(nameMessage[0])
                    .setContentText(nameMessage[1]).setTicker("New Message Arrived").setAutoCancel(true)
                    .setNumber(++numMessages);

            NotificationManager mNotificationManager = (NotificationManager) ctx
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            // mId allows you to update the notification later on.
            mNotificationManager.notify(1000, mBuilder.build());

            ChatMessageWithSelfie mChatMessage = new ChatMessageWithSelfie(recvMessage.optBoolean("direction"),
                    recvMessage.optString("message"), recvMessage.optString("selfie"),
                    recvMessage.optString("imageSent"), null);
            sessionHistory.add(mChatMessage);
            Chat.chatAdapter.add(mChatMessage);
            break;

        case Image:
            Vibrator v2 = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v2.vibrate(new long[] { 3, 100 }, -1);
            Toast.makeText(ctx, recvMessage.optString("username") + " has sent you a message!",
                    Toast.LENGTH_SHORT).show();
            ChatMessageWithSelfie mChatImageMessage = new ChatMessageWithSelfie(
                    recvMessage.optBoolean("direction"), null, recvMessage.optString("selfie"),
                    recvMessage.optString("image"), null);
            sessionHistory.add(mChatImageMessage);
            Chat.chatAdapter.add(mChatImageMessage);
            break;
        case Rectangle:
            drawingActivity.drawer.onDrawReceivedRectangle(recvMessage);
            break;
        case Circle:
            drawingActivity.drawer.onDrawReceivedCircle(recvMessage);
            break;
        case Line:
            drawingActivity.drawer.onDrawReceivedLine(recvMessage);
            break;
        case Text:
            drawingActivity.drawer.onDrawReceivedText(recvMessage);
            break;
        default:
            //ignore the message
        }
    }
}

From source file:org.kavaproject.kavatouch.internal.JSONDeviceConfiguration.java

public JSONDeviceConfiguration(Resources resources, int id) {
    InputStream jsonStream = resources.openRawResource(id);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int ctr;//from   w ww  .  j  a  v  a2  s.c o m
    try {
        ctr = jsonStream.read();
        while (ctr != -1) {
            byteArrayOutputStream.write(ctr);
            ctr = jsonStream.read();
        }
        jsonStream.close();
    } catch (IOException e) {
        throw new Error(e);
    }
    try {
        JSONObject jConfiguration = new JSONObject(byteArrayOutputStream.toString());
        flipYAxis = jConfiguration.getBoolean("flipYAxis");
        useIPadTheme = jConfiguration.getBoolean("useIPadTheme");
        JSONArray jDeviceModifiers = jConfiguration.getJSONArray("deviceModifiers");
        for (int i = 0; i < jDeviceModifiers.length(); i++) {
            deviceModifiers.add(jDeviceModifiers.getString(i));
        }
        JSONArray jImageScaleModifiers = jConfiguration.getJSONArray("imageScaleModifiers");
        for (int i = 0; i < jImageScaleModifiers.length(); i++) {
            imageScaleModifiers.add(ImageScaleModifier.createFromJSON(jImageScaleModifiers.getJSONObject(i)));
        }
        double scale = jConfiguration.optDouble("scale");
        if (Double.isNaN(scale)) {
            DisplayMetrics displayMetrics = resources.getDisplayMetrics();
            this.scale = displayMetrics.density;
        } else {
            this.scale = (float) scale;
        }
    } catch (JSONException e) {
        throw new Error(e);
    }
}

From source file:edu.asu.bscs.csiebler.waypointapplication.WaypointServerStub.java

/**
 *
 * @param from/*from w ww. ja v a2s .c o m*/
 * @param to
 * @return
 */
public double distanceGCTo(String from, String to) {
    double result = 0;

    try {
        String jsonStr = this.packageWaypointCall("distanceGCTo", from, to);
        debug("sending: " + jsonStr);
        String resString = server.call(jsonStr);
        debug("got back: " + resString);
        JSONObject res = new JSONObject(resString);
        result = res.optDouble("result");
    } catch (Exception ex) {
        System.out.println("exception in rpc call to distanceGCTo: " + ex.getMessage());
    }

    return result;
}

From source file:edu.asu.bscs.csiebler.waypointapplication.WaypointServerStub.java

/**
 *
 * @param from/*  www .  j a  va2s . c  o  m*/
 * @param to
 * @return
 */
public double bearingGCInitTo(String from, String to) {
    double result = 0;

    try {
        String jsonStr = this.packageWaypointCall("bearingGCInitTo", from, to);
        debug("sending: " + jsonStr);
        String resString = server.call(jsonStr);
        debug("got back: " + resString);
        JSONObject res = new JSONObject(resString);
        result = res.optDouble("result");
    } catch (Exception ex) {
        System.out.println("exception in rpc call to bearingGCInitTo: " + ex.getMessage());
    }

    return result;
}

From source file:fr.cph.stock.android.entity.EntityBuilder.java

private List<Equity> buildEquities(JSONArray array) throws JSONException {
    List<Equity> equities = new ArrayList<Equity>();
    boolean find = true;
    int i = 0;/* w  ww.  jav  a 2  s . c  o  m*/
    JSONObject temp;

    while (find) {
        temp = array.optJSONObject(i);
        if (temp != null) {
            Equity e = new Equity();
            e.setName(temp.getString("name"));

            double unitCostPrice = temp.getDouble("unitCostPrice");
            e.setUnitCostPrice(formatLocaleTwo.format(unitCostPrice));

            e.setValue(formatLocaleZero.format(temp.getDouble("value")));
            double plusMinusValue = temp.getDouble("plusMinusValue");
            String plusMinusValueStr = formatLocaleOne.format(plusMinusValue) + "%";
            if (plusMinusValue > 0) {
                e.setPlusMinusValue("+" + plusMinusValueStr);
            } else {
                e.setPlusMinusValue(plusMinusValueStr);
            }
            e.setUp(plusMinusValue > 0 ? true : false);

            double quantity = temp.getDouble("quantity");
            e.setQuantity(formatLocaleOne.format(quantity));

            double yieldYear = temp.getDouble("yieldYear");
            e.setYieldYear(formatLocaleOne.format(yieldYear) + "%");

            double yieldUnitCostPrice = temp.getDouble("yieldUnitCostPrice");
            e.setYieldUnitCostPrice(formatLocaleOne.format(yieldUnitCostPrice) + "%");

            double quote = temp.getDouble("quote");
            e.setQuote(formatLocaleTwo.format(quote));

            double plusMinusUnitCostPriceValue = temp.getDouble("plusMinusUnitCostPriceValue");
            if (plusMinusValue > 0) {
                e.setPlusMinusUnitCostPriceValue("+" + formatLocaleZero.format(plusMinusUnitCostPriceValue));
            } else {
                e.setPlusMinusUnitCostPriceValue(formatLocaleZero.format(plusMinusUnitCostPriceValue));
            }
            Double variation = temp.optDouble("variation");
            if (!variation.isNaN()) {
                if (variation >= 0) {
                    e.setUpVariation(true);
                    e.setVariation("+" + formatLocaleTwo.format(variation) + "%");
                } else {
                    e.setUpVariation(false);
                    e.setVariation(formatLocaleTwo.format(variation) + "%");
                }
            } else {
                e.setUpVariation(true);
                e.setVariation("+0%");
            }
            equities.add(e);
            i++;
        } else {
            find = false;
        }
    }
    return equities;
}

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

public static Coordinate parse(JSONObject jsonObject) {
    if (jsonObject == null) {
        return null;
    }/*  w  w w. j  a  v  a  2  s .  com*/

    Coordinate coordinate = new Coordinate();
    coordinate.Longtitude = jsonObject.optDouble("longitude");
    coordinate.Latitude = jsonObject.optDouble("latitude");

    return coordinate;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.LocationObj.java

@Override
public void render(Context context, ViewGroup frame, Obj obj, boolean allowInteractions) {
    JSONObject content = obj.getJson();
    TextView valueTV = new TextView(context);
    NumberFormat df = DecimalFormat.getNumberInstance();
    df.setMaximumFractionDigits(5);//from w w w.  j  a  va2s  . co  m
    df.setMinimumFractionDigits(5);

    String msg = "I'm at " + df.format(content.optDouble(COORD_LAT)) + ", "
            + df.format(content.optDouble(COORD_LONG));

    valueTV.setText(msg);
    valueTV.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
    valueTV.setGravity(Gravity.TOP | Gravity.LEFT);
    frame.addView(valueTV);
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.LocationObj.java

@Override
public void activate(Context context, SignedObj obj) {
    JSONObject content = obj.getJson();
    String loc = "geo:" + content.optDouble(COORD_LAT) + "," + content.optDouble(COORD_LONG) + "?z=17";
    Intent map = new Intent(Intent.ACTION_VIEW, Uri.parse(loc));
    context.startActivity(map);//  w ww. j  ava  2s. c  om
}

From source file:com.melniqw.instagramsdk.UserInPhoto.java

public static UserInPhoto fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    UserInPhoto userInPhoto = new UserInPhoto();
    JSONObject positionJSON = o.optJSONObject("position");
    userInPhoto.position.x = positionJSON.optDouble("x");
    userInPhoto.position.y = positionJSON.optDouble("y");
    JSONObject userJSON = o.optJSONObject("user");
    userInPhoto.user = User.fromJSON(userJSON);
    return userInPhoto;
}

From source file:com.melniqw.instagramsdk.Location.java

public static Location fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Location location = new Location();
    location.id = o.optString("id");
    location.name = o.optString("name");
    location.latitude = o.optDouble("latitude");
    location.longitude = o.optDouble("longitude");
    return location;
}