Example usage for org.json JSONArray optString

List of usage examples for org.json JSONArray optString

Introduction

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

Prototype

public String optString(int index, String defaultValue) 

Source Link

Document

Get the optional string associated with an index.

Usage

From source file:com.battlelancer.seriesguide.extensions.ExtensionManager.java

private synchronized void loadSubscriptions() {
    mEnabledExtensions = new ArrayList<>();
    mSubscriptions = new HashMap<>();
    mTokens = new HashMap<>();

    String serializedSubscriptions = mSharedPrefs.getString(PREF_SUBSCRIPTIONS, null);
    if (serializedSubscriptions == null) {
        setDefaultEnabledExtensions();/*from   w  w w .  j  a  v  a  2 s  . co  m*/
        return;
    }

    JSONArray jsonArray;
    try {
        jsonArray = new JSONArray(serializedSubscriptions);
    } catch (JSONException e) {
        Timber.e(e, "Deserializing subscriptions failed");
        return;
    }

    for (int i = 0; i < jsonArray.length(); i++) {
        String subscription = jsonArray.optString(i, null);
        if (subscription == null) {
            continue;
        }
        String[] arr = subscription.split("\\|", 2);
        ComponentName extension = ComponentName.unflattenFromString(arr[0]);
        String token = arr[1];
        mEnabledExtensions.add(extension);
        mSubscriptions.put(extension, token);
        mTokens.put(token, extension);
        Timber.d("Restored subscription: " + extension + " token: " + token);
    }
}

From source file:com.adobe.phonegap.contentsync.Sync.java

private void sync(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    // get args/*w  w w. j  a  va2s.  c om*/
    final String src = args.getString(0);
    final String id = args.getString(1);
    final JSONObject headers;
    if (args.optJSONObject(3) != null) {
        headers = args.optJSONObject(3);
    } else {
        headers = new JSONObject();
    }
    final boolean copyCordovaAssets;
    final boolean copyRootApp = args.getBoolean(5);
    final boolean trustEveryone = args.getBoolean(7);
    if (copyRootApp) {
        copyCordovaAssets = true;
    } else {
        copyCordovaAssets = args.getBoolean(4);
    }
    final String manifestFile = args.getString(8);
    Log.d(LOG_TAG, "sync called with id = " + id + " and src = " + src + "!");

    final ProgressEvent progress = createProgressEvent(id);

    /**
     * need to clear cache or Android won't pick up on the replaced
     * content
     */
    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {
            webView.clearCache(true);
        }
    });

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            synchronized (progress) {
                if (progress.isAborted()) {
                    return;
                }
            }

            String outputDirectory = getOutputDirectory(id);

            // Check to see if we should just return the cached version
            String type = args.optString(2, TYPE_REPLACE);
            Log.d(LOG_TAG, "type = " + type);
            File dir = new File(outputDirectory);
            Log.d(LOG_TAG, "dir = " + dir.exists());

            if (type.equals(TYPE_LOCAL) && !dir.exists()) {
                if ("null".equals(src) && (copyRootApp || copyCordovaAssets)) {
                    if (copyRootApp) {
                        copyRootApp(outputDirectory, manifestFile);
                    }
                    if (copyCordovaAssets) {
                        copyCordovaAssets(outputDirectory);
                    }

                } else {
                    type = TYPE_REPLACE;
                }
            }

            if (!dir.exists()) {
                dir.mkdirs();
            }

            if (!type.equals(TYPE_LOCAL)) {
                // download file
                if (download(src, createDownloadFileLocation(id), headers, progress, callbackContext,
                        trustEveryone)) {
                    // update progress with zip file
                    File targetFile = progress.getTargetFile();
                    Log.d(LOG_TAG, "downloaded = " + targetFile.getAbsolutePath());

                    // Backup existing directory
                    File backup = backupExistingDirectory(outputDirectory, type, dir);

                    // @TODO: Do we do this even when type is local?
                    if (copyRootApp) {
                        copyRootApp(outputDirectory, manifestFile);
                    }

                    boolean win = false;
                    if (isZipFile(targetFile)) {
                        win = unzipSync(targetFile, outputDirectory, progress, callbackContext);
                    } else {
                        // copy file to ID
                        win = targetFile.renameTo(new File(outputDirectory));
                        progress.setLoaded(1);
                        progress.setTotal(1);
                        progress.setStatus(STATUS_EXTRACTING);
                        progress.updatePercentage();
                    }

                    // delete temp file
                    targetFile.delete();

                    if (copyCordovaAssets) {
                        copyCordovaAssets(outputDirectory);
                    }

                    if (win) {
                        // success, remove backup
                        removeFolder(backup);
                    } else {
                        // failure, revert backup
                        removeFolder(dir);
                        backup.renameTo(dir);
                    }
                } else {
                    return;
                }
            }

            // complete
            synchronized (activeRequests) {
                activeRequests.remove(id);
            }

            // Send last progress event
            progress.setStatus(STATUS_COMPLETE);
            updateProgress(callbackContext, progress);

            // Send completion message
            try {
                JSONObject result = new JSONObject();
                result.put(PROP_LOCAL_PATH, outputDirectory);
                result.put(PROP_CACHED, type.equals(TYPE_LOCAL));
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
            } catch (JSONException e) {
                // never happens
            }
        }
    });
}

From source file:fr.louisbl.cordova.gpslocation.CordovaGPSLocation.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action/*from  w w  w  . jav a 2  s .  c  o  m*/
 *            The action to execute.
 * @param args
 *            JSONArry of arguments for the plugin.
 * @param callbackContext
 *            The callback id used when calling back into JavaScript.
 * @return True if the action was valid, or false if not.
 * @throws JSONException
 */
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) {

    if (action == null || !action.matches("getLocation|addWatch|clearWatch")) {
        return false;
    }

    final String id = args.optString(0, "");

    if (action.equals("clearWatch")) {
        clearWatch(id);
        return true;
    }

    if (isGPSdisabled()) {
        fail(CordovaLocationListener.POSITION_UNAVAILABLE, "GPS is disabled on this device.", callbackContext,
                false);
        return true;
    }

    if (action.equals("getLocation")) {
        getLastLocation(args, callbackContext);
    } else if (action.equals("addWatch")) {
        addWatch(id, callbackContext);
    }

    return true;
}

From source file:com.mikecorrigan.trainscorekeeper.Players.java

@SuppressLint("NewApi")
public Players(final Activity context, ViewGroup viewGroup, final JSONArray jsonPlayers) {
    Log.vc(VERBOSE, TAG,/*  w w w. ja v  a  2 s .  co  m*/
            "ctor: context=" + context + ", viewGroup=" + viewGroup + ", jsonPlayers=" + jsonPlayers);

    viewGroup.removeAllViews();

    Resources resources = context.getResources();

    String[] playerNames = resources.getStringArray(R.array.playerNames);

    TypedArray drawablesArray = resources.obtainTypedArray(R.array.playerDrawables);

    TypedArray colorIdsArray = resources.obtainTypedArray(R.array.playerTextColors);
    int[] colorIds = new int[colorIdsArray.length()];
    for (int i = 0; i < colorIdsArray.length(); i++) {
        colorIds[i] = colorIdsArray.getResourceId(i, -1);
    }

    listeners = new HashSet<Listener>();
    players = new SparseArray<Player>();

    for (int i = 0; i < playerNames.length; i++) {
        PlayerButton toggleButton = new PlayerButton(context);
        toggleButton.setPlayerId(i);
        LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, 1f);
        toggleButton.setLayoutParams(layoutParams);
        Drawable drawable = drawablesArray.getDrawable(i);
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            toggleButton.setBackgroundDrawable(drawable);
        } else {
            toggleButton.setBackground(drawable);
        }
        toggleButton.setPadding(10, 10, 10, 10);
        toggleButton.setTextColor(resources.getColor(colorIds[i]));
        toggleButton.setOnClickListener(onSelect);

        viewGroup.addView(toggleButton);

        final String name = playerNames[i];

        boolean enabled = true;

        // If the players configuration is available, determine which players are enabled.
        if (jsonPlayers != null) {
            enabled = false;
            for (int j = 0; j < jsonPlayers.length(); j++) {
                String jsonName = jsonPlayers.optString(j, "");
                if (jsonName.equalsIgnoreCase(name)) {
                    enabled = true;
                    break;
                }
            }
        }

        Player player = new Player(toggleButton, i, name, enabled);
        players.put(i, player);
    }

    setSelection(-1);

    drawablesArray.recycle();
    colorIdsArray.recycle();
}