Example usage for org.json JSONArray getString

List of usage examples for org.json JSONArray getString

Introduction

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

Prototype

public String getString(int index) throws JSONException 

Source Link

Document

Get the string associated with an index.

Usage

From source file:com.coloreight.plugin.clipboard.Clipboard.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals(ACTION_COPY)) {
        this.copy(args.getString(0), callbackContext);
    } else if (action.equals(ACTION_PASTE)) {
        this.paste(callbackContext);
    } else {/*from w ww .ja va2s  .  c o  m*/
        return false;
    }

    return true;
}

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 w  ww. j  a va  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:nl.cup_a_sep.ovalarm.plugin.StatusBarNotification.java

/**
 *    Executes the request and returns PluginResult
 *
 *    @param action      Action to execute
 *    @param data         JSONArray of arguments to the plugin
 *  @param callbackContext   The callback context used when calling back into JavaScript.
 *
 *  @return            A PluginRequest object with a status
 * *//*w w w  .ja  v a  2  s  .co m*/
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
    boolean actionValid = true;
    if (NOTIFY.equals(action)) {
        try {
            String tag = data.getString(0);
            String title = data.getString(1);
            String body = data.getString(2);
            String flag = data.getString(3);
            int notificationFlag = getFlagValue(flag);
            Log.d("NotificationPlugin",
                    "Notification: " + tag + ", " + title + ", " + body + ", " + notificationFlag);
            showNotification(tag, title, body, notificationFlag);
        } catch (JSONException jsonEx) {
            Log.d("NotificationPlugin", "Got JSON Exception " + jsonEx.getMessage());
            actionValid = false;
        }
    } else if (CLEAR.equals(action)) {
        try {
            String tag = data.getString(0);
            Log.d("NotificationPlugin", "Notification cancel: " + tag);
            clearNotification(tag);
        } catch (JSONException jsonEx) {
            Log.d("NotificationPlugin", "Got JSON Exception " + jsonEx.getMessage());
            actionValid = false;
        }
    } else {
        actionValid = false;
        Log.d("NotificationPlugin", "Invalid action : " + action + " passed");
    }
    return actionValid;
}

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

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    Log.d(TAG, action + " " + args.length());

    if (action.equals("init")) {
        this.init(args, callbackContext);
        return true;
    } else if (action.equals("startCamera")) {
        this.startPreview(args.getString(0), getDoubleOrNull(args, 1), callbackContext);

        return true;
    } else if (action.equals("stopCamera")) {
        this.stopPreview(callbackContext);

        return true;
    } else if (action.equals("setZoom")) {
        this.setZoom(getDoubleOrNull(args, 0), callbackContext);

        return true;
    } else if (action.equals("setFocus")) {
        this.setFocus(getIntOrNull(args, 0), getIntOrNull(args, 1), callbackContext);

        return true;
    } else if (action.equals("resetFocus")) {
        this.resetFocus(callbackContext);

        return true;
    }/*from ww  w .j a v a  2s .c o m*/

    return false;
}

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

private void init(JSONArray args, final CallbackContext callbackContext) {
    this.callbackContext = callbackContext;

    supportSnapshot = getSnapshotPlugin() != null;

    if (args != null) {
        String rgb = DEFAULT_RGB;
        try {/*from   w  ww.ja  v  a2s  .c  om*/
            rgb = args.getString(0);
        } catch (JSONException e) {
            //do nothing; resort to DEFAULT_RGB
        }

        setBackgroundColor(Color.parseColor(rgb));
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewView.setBackgroundColor(getBackgroundColor());
            }
        });
    }

    if (!PermissionHelper.hasPermission(this, permissions[0])) {
        PermissionHelper.requestPermission(this, CAMERA_SEC, Manifest.permission.CAMERA);
        return;
    }

    JSONObject jsonObject = new JSONObject();
    try {
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics m = new DisplayMetrics();
        display.getMetrics(m);

        jsonObject.put("displayWidth", m.widthPixels);
        jsonObject.put("displayHeight", m.heightPixels);

        int mNumberOfCameras = Camera.getNumberOfCameras();
        Log.d(TAG, "Cameras:" + mNumberOfCameras);

        // Find the ID of the back-facing ("default") camera
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < mNumberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);

            Parameters parameters;
            Camera open = null;
            try {
                open = Camera.open(i);
                parameters = open.getParameters();
            } finally {
                if (open != null) {
                    open.release();
                }
            }

            Log.d(TAG, "Camera facing:" + cameraInfo.facing);

            CameraDirection type = null;
            for (CameraDirection f : CameraDirection.values()) {
                if (f.getDirection() == cameraInfo.facing) {
                    type = f;
                }
            }

            if (type != null) {
                double zoom = 0;
                double maxZoom = 0;
                if (parameters.isZoomSupported()) {
                    maxZoom = (parameters.getMaxZoom() + 1) / 10.0;
                    zoom = Math.min(parameters.getZoom() / 10.0 + 1, maxZoom);
                }

                JSONObject jsonCamera = new JSONObject();
                jsonCamera.put("id", i);
                jsonCamera.put("position", type.toString());
                jsonCamera.put("zoom", zoom);
                jsonCamera.put("maxZoom", maxZoom);
                jsonObject.put(type.toString(), jsonCamera);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Can't set exception", e);
    }

    callbackContext.success(jsonObject);
}

From source file:com.hichinaschool.flashcards.anki.CardEditor.java

private void setNote(Note note) {
    try {/*from  w  w  w . j av  a2 s.  com*/
        if (note == null) {
            mCurrentDid = mCol.getDecks().current().getLong("id");
            if (mCol.getDecks().isDyn(mCurrentDid)) {
                mCurrentDid = 1;
            }

            JSONObject model = mCol.getModels().current();
            mEditorNote = new Note(mCol, model);
            mEditorNote.model().put("did", mCurrentDid);
            mModelButton.setText(getResources().getString(R.string.CardEditorModel, model.getString("name")));
            JSONArray tags = model.getJSONArray("tags");
            for (int i = 0; i < tags.length(); i++) {
                mEditorNote.addTag(tags.getString(i));
            }
        } else {
            mEditorNote = note;
            mCurrentDid = mCurrentEditedCard.getDid();
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    mCurrentTags = mEditorNote.getTags();
    updateDeck();
    updateTags();
    populateEditFields();
    swapText(true);
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;//w  w w .  j  a  v a 2 s .  c  o  m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();

    if (title != null && title.length() > 0) {
        newTexts.add(title);
    }

    if (authors != null && !authors.isEmpty()) {
        boolean first = true;
        StringBuilder authorsText = new StringBuilder();
        for (String author : authors) {
            if (first) {
                first = false;
            } else {
                authorsText.append(", ");
            }
            authorsText.append(author);
        }
        newTexts.add(authorsText.toString());
    }

    if (pages != null && pages.length() > 0) {
        newTexts.add(pages + "pp.");
    }

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:it.readbeyond.minstrel.media.AudioHandler.java

/**
 * Executes the request and returns PluginResult.
 * @param action       The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackContext      The callback context used when calling back into JavaScript.
 * @return             A PluginResult object with a status and message.
 *///from  w ww.j ava 2s.  com
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    CordovaResourceApi resourceApi = webView.getResourceApi();
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    if (action.equals("startPlayingAudio")) {
        String target = args.getString(1);
        String fileUriStr;
        try {
            Uri targetUri = resourceApi.remapUri(Uri.parse(target));
            fileUriStr = targetUri.toString();
        } catch (IllegalArgumentException e) {
            fileUriStr = target;
        }
        this.startPlayingAudio(args.getString(0), FileHelper.stripFileProtocol(fileUriStr));
    } else if (action.equals("seekToAudio")) {
        this.seekToAudio(args.getString(0), args.getInt(1));
    } else if (action.equals("pausePlayingAudio")) {
        this.pausePlayingAudio(args.getString(0));
    } else if (action.equals("stopPlayingAudio")) {
        this.stopPlayingAudio(args.getString(0));
    } else if (action.equals("setVolume")) {
        try {
            this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));
        } catch (NumberFormatException nfe) {
            //no-op
        }
    } else if (action.equals("getCurrentPositionAudio")) {
        float f = this.getCurrentPositionAudio(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("getDurationAudio")) {
        float f = this.getDurationAudio(args.getString(0), args.getString(1));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("create")) {
        String id = args.getString(0);
        String src = FileHelper.stripFileProtocol(args.getString(1));
        getOrCreatePlayer(id, src);
    } else if (action.equals("release")) {
        boolean b = this.release(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, b));
        return true;
    } else if (action.equals("messageChannel")) {
        messageChannel = callbackContext;
        return true;
    } else { // Unrecognized action.
        return false;
    }

    callbackContext.sendPluginResult(new PluginResult(status, result));

    return true;
}

From source file:com.miz.service.TraktTvShowsSyncService.java

private void downloadTvShowCollection() {
    JSONArray jsonArray = Trakt.getTvShowLibrary(this, Trakt.COLLECTION);
    if (jsonArray.length() > 0) {
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                String id = String.valueOf(jsonArray.getJSONObject(i).getString("tvdb_id"));
                TraktTvShow show = new TraktTvShow(id, jsonArray.getJSONObject(i).getString("title"));

                JSONArray seasons = jsonArray.getJSONObject(i).getJSONArray("seasons");
                for (int j = 0; j < seasons.length(); j++) {
                    String season = seasons.getJSONObject(j).getString("season");
                    JSONArray episodes = seasons.getJSONObject(j).getJSONArray("episodes");
                    for (int k = 0; k < episodes.length(); k++) {
                        show.addEpisode(season, episodes.getString(k));
                    }//  w ww .  j  a  va2 s. c o m
                }

                mTraktCollection.put(id, show);
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.miz.service.TraktTvShowsSyncService.java

private void downloadWatchedTvShows() {
    JSONArray jsonArray = Trakt.getTvShowLibrary(this, Trakt.WATCHED);
    if (jsonArray.length() > 0) {
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                String showId = String.valueOf(jsonArray.getJSONObject(i).getString("tvdb_id"));
                TraktTvShow show = new TraktTvShow(showId, jsonArray.getJSONObject(i).getString("title"));

                JSONArray seasons = jsonArray.getJSONObject(i).getJSONArray("seasons");
                for (int j = 0; j < seasons.length(); j++) {
                    String season = seasons.getJSONObject(j).getString("season");
                    JSONArray episodes = seasons.getJSONObject(j).getJSONArray("episodes");
                    for (int k = 0; k < episodes.length(); k++) {
                        show.addEpisode(season, episodes.getString(k));
                    }/* w  ww  . j  a v  a 2  s. c  o  m*/
                }
                mTraktWatched.put(showId, show);

                if (mShowIds.contains(String.valueOf(jsonArray.getJSONObject(i).get("tvdb_id")))) {
                    for (int j = 0; j < seasons.length(); j++) {
                        JSONObject season = seasons.getJSONObject(j);
                        String seasonNumber = MizLib.addIndexZero(String.valueOf(season.get("season")));
                        JSONArray seasonEpisodes = season.getJSONArray("episodes");
                        for (int k = 0; k < seasonEpisodes.length(); k++) {
                            mEpisodeDatabase.updateEpisode(showId, seasonNumber,
                                    MizLib.addIndexZero(String.valueOf(seasonEpisodes.get(k))),
                                    DbAdapterTvShowEpisodes.KEY_HAS_WATCHED, "1");
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
    }
}