Example usage for org.json JSONArray getDouble

List of usage examples for org.json JSONArray getDouble

Introduction

In this page you can find the example usage for org.json JSONArray getDouble.

Prototype

public double getDouble(int index) throws JSONException 

Source Link

Document

Get the double value associated with an index.

Usage

From source file:com.google.android.apps.body.LayersLoader.java

/** Synchronously loads a single layer. */
private Render.DrawGroup[] load(Context context, int layerResource) {
    // TODO(thakis): this method is kinda ugly.
    // TODO(thakis): if we can bundle the resource files, rewrite them so that no conversion
    //               needs to happen at load time. The utf8 stuff is clever, but mostly overhead
    //               for local files.

    // Timers for different loading phases.
    float jsonReadS = 0;
    float jsonParseS = 0;
    float textureS = 0;
    float fileReadS = 0;
    float fileDecodeS = 0;
    float colorBufferS = 0;

    Render.DrawGroup[] drawGroups = null;

    long jsonReadStartNS = System.nanoTime();
    JSONObject object = loadJsonResource(context, layerResource);
    jsonReadS = (System.nanoTime() - jsonReadStartNS) / 1e9f;

    long jsonParseStartNS = System.nanoTime();
    Map<Integer, List<Loader>> toBeLoaded = new HashMap<Integer, List<Loader>>();
    try {/*from  w ww  .  j ava 2 s  .c om*/
        JSONArray dataDrawGroups = object.getJSONArray("draw_groups");
        drawGroups = new Render.DrawGroup[dataDrawGroups.length()];
        for (int i = 0; i < drawGroups.length; ++i) {
            if (mCancelled)
                return null;

            JSONObject drawGroup = dataDrawGroups.getJSONObject(i);
            drawGroups[i] = new Render.DrawGroup();
            if (drawGroup.has("texture"))
                drawGroups[i].texture = drawGroup.getString("texture");
            else if (drawGroup.has("diffuse_color")) {
                JSONArray color = drawGroup.getJSONArray("diffuse_color");
                drawGroups[i].diffuseColor = new float[3];
                for (int j = 0; j < 3; ++j)
                    drawGroups[i].diffuseColor[j] = (float) color.getDouble(j);
            }
            JSONArray draws = drawGroup.getJSONArray("draws");
            drawGroups[i].draws = new ArrayList<Render.Draw>(draws.length());
            for (int j = 0; j < draws.length(); ++j) {
                JSONObject jsonDraw = draws.getJSONObject(j);
                Render.Draw draw = new Render.Draw();
                draw.geometry = jsonDraw.getString("geometry");
                draw.offset = jsonDraw.getJSONArray("range").getInt(0);
                draw.count = jsonDraw.getJSONArray("range").getInt(1);
                drawGroups[i].draws.add(draw);
            }
            long textureReadStartNS = System.nanoTime();
            loadTexture(mContext, drawGroups[i]);
            textureS += (System.nanoTime() - textureReadStartNS) / 1e9f;

            String indices = drawGroup.getString("indices");
            FP.FPEntry indicesFP = FP.get(indices);
            if (toBeLoaded.get(indicesFP.file) == null)
                toBeLoaded.put(indicesFP.file, new ArrayList<Loader>());
            toBeLoaded.get(indicesFP.file).add(new IndexLoader(drawGroups[i], indicesFP));

            String attribs = drawGroup.getString("attribs");
            FP.FPEntry attribsFP = FP.get(attribs);
            if (toBeLoaded.get(attribsFP.file) == null)
                toBeLoaded.put(attribsFP.file, new ArrayList<Loader>());
            toBeLoaded.get(attribsFP.file).add(new AttribLoader(drawGroups[i], attribsFP));

            drawGroups[i].numIndices = drawGroup.getInt("numIndices");
        }
    } catch (JSONException e) {
        Log.e("Body", e.toString());
    }
    jsonParseS = (System.nanoTime() - jsonParseStartNS) / 1e9f - textureS;

    for (int resource : toBeLoaded.keySet()) {
        if (mCancelled)
            return null;

        long fileReadStartNS = System.nanoTime();
        char[] data = new char[0];
        InputStream is = mContext.getResources().openRawResource(resource);
        try {
            // Comment from the ApiDemo content/ReadAsset.java in the Android SDK:
            // "We guarantee that the available method returns the total
            //  size of the asset...  of course, this does mean that a single
            //  asset can't be more than 2 gigs."
            data = new char[is.available()];
            Reader in = new InputStreamReader(is, "UTF-8");
            in.read(data, 0, data.length);
        } catch (UnsupportedEncodingException e) {
            Log.e("Body", e.toString());
        } catch (IOException e) {
            Log.e("Body", e.toString());
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                Log.e("Body", e.toString());
            }
        }
        fileReadS += (System.nanoTime() - fileReadStartNS) / 1.0e9f;
        long fileDecodeStartNS = System.nanoTime();
        for (Loader l : toBeLoaded.get(resource)) {
            if (mCancelled)
                return null;

            l.load(data);
        }
        fileDecodeS += (System.nanoTime() - fileDecodeStartNS) / 1.0e9f;
    }

    long colorBufferStartNS = System.nanoTime();
    for (Render.DrawGroup drawGroup : drawGroups) {
        if (mCancelled)
            return null;
        createColorBuffer(drawGroup);
    }
    colorBufferS = (System.nanoTime() - colorBufferStartNS) / 1e9f;

    Log.i("Body", "JSON read: " + jsonReadS + ", JSON parse: " + jsonParseS + ", texture: " + textureS
            + ", res read: " + fileReadS + ", res decode: " + fileDecodeS + ", colorbuf: " + colorBufferS);

    return drawGroups;
}

From source file:oculus.aperture.common.JSONProperties.java

@Override
public Iterable<Float> getFloats(String key) {
    try {/*w w w .  j a v  a  2 s . co  m*/
        final JSONArray array = obj.getJSONArray(key);

        return new Iterable<Float>() {
            @Override
            public Iterator<Float> iterator() {
                return new Iterator<Float>() {
                    private final int n = array.length();
                    private int i = 0;

                    @Override
                    public boolean hasNext() {
                        return n > i;
                    }

                    @Override
                    public Float next() {
                        try {
                            return (n > i) ? (float) array.getDouble(i++) : null;
                        } catch (JSONException e) {
                            return null;
                        }
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };

    } catch (JSONException e) {
        return EmptyIterable.instance();
    }
}

From source file:oculus.aperture.common.JSONProperties.java

@Override
public Iterable<Double> getDoubles(String key) {
    try {/*  w ww  .jav  a 2  s .co m*/
        final JSONArray array = obj.getJSONArray(key);

        return new Iterable<Double>() {
            @Override
            public Iterator<Double> iterator() {
                return new Iterator<Double>() {
                    private final int n = array.length();
                    private int i = 0;

                    @Override
                    public boolean hasNext() {
                        return n > i;
                    }

                    @Override
                    public Double next() {
                        try {
                            return (n > i) ? array.getDouble(i++) : null;
                        } catch (JSONException e) {
                            return null;
                        }
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };

    } catch (JSONException e) {
        return EmptyIterable.instance();
    }
}

From source file:com.mm.yamingapp.core.MethodDescriptor.java

/**
 * Converts a parameter from JSON into a Java Object.
 * //from  w  ww .  jav a  2  s  .  c om
 * @return TODO
 */
// TODO(damonkohler): This signature is a bit weird (auto-refactored). The obvious alternative
// would be to work on one supplied parameter and return the converted parameter. However, that's
// problematic because you lose the ability to call the getXXX methods on the JSON array.
@VisibleForTesting
static Object convertParameter(final JSONArray parameters, int index, Type type)
        throws JSONException, RpcError {
    try {
        // We must handle null and numbers explicitly because we cannot magically cast them. We
        // also need to convert implicitly from numbers to bools.
        if (parameters.isNull(index)) {
            return null;
        } else if (type == Boolean.class) {
            try {
                return parameters.getBoolean(index);
            } catch (JSONException e) {
                return new Boolean(parameters.getInt(index) != 0);
            }
        } else if (type == Long.class) {
            return parameters.getLong(index);
        } else if (type == Double.class) {
            return parameters.getDouble(index);
        } else if (type == Integer.class) {
            return parameters.getInt(index);
        } else {
            // Magically cast the parameter to the right Java type.
            return ((Class<?>) type).cast(parameters.get(index));
        }
    } catch (ClassCastException e) {
        throw new RpcError(
                "Argument " + (index + 1) + " should be of type " + ((Class<?>) type).getSimpleName() + ".");
    }
}

From source file:it.mb.whatshare.Utils.java

/**
 * Decodes a matrix encoded using {@link #matrixToJson(Matrix)} from JSON
 * format to a {@link Matrix} object./*from   ww w.j  a va  2s  . c  o m*/
 * 
 * @param array
 *            the encoded matrix
 * @return a matrix containing values from the JSON string (probably not
 *         100% equal to the original because of the
 *         <tt>float --&gt; double --&gt; float</tt> conversion) or
 *         <code>null</code> if <tt>array</tt> is <code>null</code> or
 *         doesn't contain a matrix
 */
public static Matrix jsonToMatrix(JSONArray array) {
    if (array == null)
        return null;
    float[] values = new float[9];
    Matrix matrix = new Matrix();
    for (int i = 0; i < array.length(); i++) {
        try {
            values[i] = (float) array.getDouble(i);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
    matrix.setValues(values);
    return matrix;
}

From source file:com.mmclass.libsiren.Util.java

public static float[] getFloatArray(SharedPreferences pref, String key) {
    float[] array = null;
    String s = pref.getString(key, null);
    if (s != null) {
        try {//  ww w .j a v  a2s  . co m
            JSONArray json = new JSONArray(s);
            array = new float[json.length()];
            for (int i = 0; i < array.length; i++)
                array[i] = (float) json.getDouble(i);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return array;
}

From source file:com.imaginary.home.cloud.device.Light.java

static void mapLight(@Nonnull ControllerRelay relay, @Nonnull JSONObject json,
        @Nonnull Map<String, Object> state) throws JSONException {
    mapPoweredDevice(relay, json, state);
    state.put("deviceType", "light");
    if (json.has("color")) {
        JSONObject color = json.getJSONObject("color");
        ColorMode colorMode = null;/*  w  w w. j  a  v a 2  s  .  co  m*/
        float[] components = null;

        if (color.has("colorMode") && !color.isNull("colorMode")) {
            try {
                colorMode = ColorMode.valueOf(color.getString("colorMode"));
            } catch (IllegalArgumentException e) {
                throw new JSONException("Invalid color mode: " + color.getString("colorMode"));
            }
        }
        if (color.has("components") && !color.isNull("components")) {
            JSONArray arr = color.getJSONArray("components");
            components = new float[arr.length()];

            for (int i = 0; i < arr.length(); i++) {
                components[i] = (float) arr.getDouble(i);
            }
        }
        if (colorMode != null || components != null) {
            state.put("colorMode", colorMode);
            state.put("colorValues", components);
        }
    }
    if (json.has("brightness") && !json.isNull("brightness")) {
        state.put("brightness", (float) json.getDouble("brightness"));
    }
    if (json.has("supportsColorChanges")) {
        state.put("colorChangeSupported",
                !json.isNull("supportsColorChanges") && json.getBoolean("supportsColorChanges"));
    }
    if (json.has("supportsBrightnessChanges")) {
        state.put("dimmable",
                !json.isNull("supportsBrightnessChanges") && json.getBoolean("supportsBrightnessChanges"));
    }
    if (json.has("colorModes")) {
        JSONArray arr = json.getJSONArray("colorModes");
        ColorMode[] modes = new ColorMode[arr.length()];

        for (int i = 0; i < arr.length(); i++) {
            try {
                modes[i] = ColorMode.valueOf(arr.getString(i));
            } catch (IllegalArgumentException e) {
                throw new JSONException("Invalid color mode: " + arr.getString(i));
            }
        }
        state.put("colorModesSupported", modes);
    }
}

From source file:com.trk.aboutme.facebook.SharedPreferencesTokenCachingStrategy.java

private void deserializeKey(String key, Bundle bundle) throws JSONException {
    String jsonString = cache.getString(key, "{}");
    JSONObject json = new JSONObject(jsonString);

    String valueType = json.getString(JSON_VALUE_TYPE);

    if (valueType.equals(TYPE_BOOLEAN)) {
        bundle.putBoolean(key, json.getBoolean(JSON_VALUE));
    } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        boolean[] array = new boolean[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getBoolean(i);
        }/*from www .j  av  a  2s .c o  m*/
        bundle.putBooleanArray(key, array);
    } else if (valueType.equals(TYPE_BYTE)) {
        bundle.putByte(key, (byte) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_BYTE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        byte[] array = new byte[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (byte) jsonArray.getInt(i);
        }
        bundle.putByteArray(key, array);
    } else if (valueType.equals(TYPE_SHORT)) {
        bundle.putShort(key, (short) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_SHORT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        short[] array = new short[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (short) jsonArray.getInt(i);
        }
        bundle.putShortArray(key, array);
    } else if (valueType.equals(TYPE_INTEGER)) {
        bundle.putInt(key, json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int[] array = new int[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getInt(i);
        }
        bundle.putIntArray(key, array);
    } else if (valueType.equals(TYPE_LONG)) {
        bundle.putLong(key, json.getLong(JSON_VALUE));
    } else if (valueType.equals(TYPE_LONG_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        long[] array = new long[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getLong(i);
        }
        bundle.putLongArray(key, array);
    } else if (valueType.equals(TYPE_FLOAT)) {
        bundle.putFloat(key, (float) json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        float[] array = new float[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (float) jsonArray.getDouble(i);
        }
        bundle.putFloatArray(key, array);
    } else if (valueType.equals(TYPE_DOUBLE)) {
        bundle.putDouble(key, json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        double[] array = new double[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getDouble(i);
        }
        bundle.putDoubleArray(key, array);
    } else if (valueType.equals(TYPE_CHAR)) {
        String charString = json.getString(JSON_VALUE);
        if (charString != null && charString.length() == 1) {
            bundle.putChar(key, charString.charAt(0));
        }
    } else if (valueType.equals(TYPE_CHAR_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        char[] array = new char[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            String charString = jsonArray.getString(i);
            if (charString != null && charString.length() == 1) {
                array[i] = charString.charAt(0);
            }
        }
        bundle.putCharArray(key, array);
    } else if (valueType.equals(TYPE_STRING)) {
        bundle.putString(key, json.getString(JSON_VALUE));
    } else if (valueType.equals(TYPE_STRING_LIST)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int numStrings = jsonArray.length();
        ArrayList<String> stringList = new ArrayList<String>(numStrings);
        for (int i = 0; i < numStrings; i++) {
            Object jsonStringValue = jsonArray.get(i);
            stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue);
        }
        bundle.putStringArrayList(key, stringList);
    } else if (valueType.equals(TYPE_ENUM)) {
        try {
            String enumType = json.getString(JSON_VALUE_ENUM_TYPE);
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType);
            @SuppressWarnings("unchecked")
            Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE));
            bundle.putSerializable(key, enumValue);
        } catch (ClassNotFoundException e) {
        } catch (IllegalArgumentException e) {
        }
    }
}

From source file:com.ezartech.ezar.videooverlay.ezAR.java

private static double getDoubleOrNull(JSONArray args, int i) {
    if (args.isNull(i)) {
        return Double.NaN;
    }/*from w ww .j  a  v a  2s  .c  om*/

    try {
        return args.getDouble(i);
    } catch (JSONException e) {
        Log.e(TAG, "Can't get double", e);
        throw new RuntimeException(e);
    }
}

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

/**
 * Deserializes property with the specified name in the specified json object into a double array.
 * // w  w w. j  a  va2 s . co m
 * @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 double[] deserializeDoubleArray(JSONObject object, String name) throws SerializerException {
    try {
        if (object.has(name)) {
            JSONArray array = object.getJSONArray(name);
            double[] outArray = new double[array.length()];

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

            return outArray;
        }

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