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:oculus.aperture.common.JSONProperties.java

@Override
public Iterable<String> getStrings(String key) {
    try {// w  ww  .ja v a2  s .  c  o  m
        final JSONArray array = obj.getJSONArray(key);

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

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

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

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

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

From source file:net.idlesoft.android.apps.github.activities.Profile.java

@Override
public void onCreate(final Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.profile);//ww w. j  a  v  a 2 s  .  c  o  m

    mPrefs = getSharedPreferences(Hubroid.PREFS_NAME, 0);

    mUsername = mPrefs.getString("username", "");
    mPassword = mPrefs.getString("password", "");

    mGapi = new GitHubAPI();
    mGapi.authenticate(mUsername, mPassword);

    ((ImageButton) findViewById(R.id.btn_search)).setOnClickListener(new OnClickListener() {
        public void onClick(final View v) {
            startActivity(new Intent(Profile.this, Search.class));
        }
    });

    final Bundle extras = getIntent().getExtras();
    if (extras != null) {
        mTarget = extras.getString("username");
    }
    try {
        if ((mTarget == null) || mTarget.equals("")) {
            mTarget = mUsername;
        }
        Response userInfoResp;
        userInfoResp = mGapi.user.info(mTarget);
        if (userInfoResp.statusCode == 200) {
            mJson = new JSONObject(userInfoResp.resp);
        }
        if (mJson == null) {
            // User doesn't really exist, return to the previous activity
            this.setResult(5005);
            finish();
        } else {
            mJson = mJson.getJSONObject("user");

            final JSONArray following_list = new JSONObject(mGapi.user.following(mUsername).resp)
                    .getJSONArray("users");
            final int length = following_list.length() - 1;
            for (int i = 0; i <= length; i++) {
                if (following_list.getString(i).equalsIgnoreCase(mTarget)) {
                }
            }

            String company, location, full_name, email, blog;

            // Replace empty values with "N/A"
            if (mJson.has("company") && !mJson.getString("company").equals("null")
                    && !mJson.getString("company").equals("")) {
                company = mJson.getString("company");
            } else {
                company = "N/A";
            }
            if (mJson.has("location") && !mJson.getString("location").equals("null")
                    && !mJson.getString("location").equals("")) {
                location = mJson.getString("location");
            } else {
                location = "N/A";
            }
            if (mJson.has("name") && !mJson.getString("name").equals("null")) {
                full_name = mJson.getString("name");
            } else {
                full_name = mTarget;
            }
            if (mJson.has("email") && !mJson.getString("email").equals("null")
                    && !mJson.getString("email").equals("")) {
                email = mJson.getString("email");
            } else {
                email = "N/A";
            }
            if (mJson.has("blog") && !mJson.getString("blog").equals("null")
                    && !mJson.getString("blog").equals("")) {
                blog = mJson.getString("blog");
            } else {
                blog = "N/A";
            }

            // Set all the values in the layout
            // ((TextView)findViewById(R.id.tv_top_bar_title)).setText(m_targetUser);
            ((ImageView) findViewById(R.id.iv_user_info_gravatar)).setImageBitmap(GravatarCache.getDipGravatar(
                    GravatarCache.getGravatarID(mTarget), 50.0f, getResources().getDisplayMetrics().density));
            ((TextView) findViewById(R.id.tv_user_info_full_name)).setText(full_name);
            ((TextView) findViewById(R.id.tv_user_info_company)).setText(company);
            ((TextView) findViewById(R.id.tv_user_info_email)).setText(email);
            ((TextView) findViewById(R.id.tv_user_info_location)).setText(location);
            ((TextView) findViewById(R.id.tv_user_info_blog)).setText(blog);

            // Make the buttons work
            final Button activityBtn = (Button) findViewById(R.id.btn_user_info_public_activity);
            final Button repositoriesBtn = (Button) findViewById(R.id.btn_user_info_repositories);
            final Button followersFollowingBtn = (Button) findViewById(R.id.btn_user_info_followers_following);

            activityBtn.setOnClickListener(onButtonClick);
            repositoriesBtn.setOnClickListener(onButtonClick);
            followersFollowingBtn.setOnClickListener(onButtonClick);
        }
    } catch (final JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.polyvi.xface.extension.video.XVideoExt.java

@Override
public XExtensionResult exec(String action, JSONArray args, XCallbackContext callbackCtx) throws JSONException {
    XExtensionResult.Status status = XExtensionResult.Status.NO_RESULT;

    if (action.equals(COMMAND_PLAY)) {
        play(args.getString(0), callbackCtx);
    }/*ww w .  j  ava  2 s .c om*/

    return new XExtensionResult(status);
}

From source file:com.tassadar.multirommgr.installfragment.InstallCard.java

private int getDefaultKernel() {
    int res = 0;/*  w  w  w.java2  s  .c o  m*/
    Iterator<Map.Entry<String, Manifest.InstallationFile>> itr = m_manifest.getKernels().entrySet().iterator();
    for (int i = 0; itr.hasNext(); ++i) {
        JSONObject extra = itr.next().getValue().extra;
        if (extra == null)
            continue;
        try {
            if (extra.has("display") && Build.DISPLAY.indexOf(extra.getString("display")) == -1)
                continue;

            if (extra.has("releases")) {
                JSONArray r = extra.getJSONArray("releases");
                boolean found = false;
                for (int x = 0; x < r.length(); ++x) {
                    if (r.getString(x).equals(Build.VERSION.RELEASE)) {
                        found = true;
                        break;
                    }
                }
                if (!found)
                    continue;
            }
            res = i;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return res;
}

From source file:com.phonegap.ContactManager.java

/**
 * Executes the request and returns PluginResult.
 * //from  w  ww. j  a va  2s .  c  om
 * @param action       The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackId   The callback id used when calling back into JavaScript.
 * @return             A PluginResult object with a status and message.
 */
public PluginResult execute(String action, JSONArray args, String callbackId) {
    if (contactAccessor == null) {
        contactAccessor = ContactAccessor.getInstance(webView, ctx);
    }
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {
        if (action.equals("search")) {
            JSONArray res = contactAccessor.search(args.getJSONArray(0), args.optJSONObject(1));
            return new PluginResult(status, res, "navigator.service.contacts.cast");
        } else if (action.equals("save")) {
            return new PluginResult(status, contactAccessor.save(args.getJSONObject(0)));
        } else if (action.equals("remove")) {
            if (contactAccessor.remove(args.getString(0))) {
                return new PluginResult(status, result);
            } else {
                JSONObject r = new JSONObject();
                r.put("code", 2);
                return new PluginResult(PluginResult.Status.ERROR, r);
            }
        }
        return new PluginResult(status, result);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    }
}

From source file:com.wso2.mobile.mdm.api.DeviceInfo.java

/**
*Returns the network operator name//from   w w  w.  ja v  a2  s .c  o m
*/
public JSONArray getNetworkOperatorName() {
    JSONArray jsonArray = null;
    final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    if (CommonUtilities.DEBUG_MODE_ENABLED) {
        Log.e("Network OP", tm.getSimOperatorName());
    }
    if (tm.getSimOperatorName() != null && tm.getSimOperatorName() != "") {
        networkOperatorName = tm.getSimOperatorName();
    } else {
        networkOperatorName = "No Sim";
    }

    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);
    try {
        jsonArray = new JSONArray(mainPref.getString("operators", "[]"));
        boolean simstatus = false;
        if (jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                if ((jsonArray.getString(i) != null)
                        && jsonArray.getString(i).trim().equals(tm.getSimOperatorName())) {
                    simstatus = true;
                }
            }
            if (!simstatus) {
                jsonArray.put(tm.getSimOperatorName());
            }
        } else {
            jsonArray.put(tm.getSimOperatorName());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    Editor editor = mainPref.edit();
    editor.putString("operators", jsonArray.toString());
    editor.commit();

    return jsonArray;
}

From source file:org.protorabbit.json.DefaultSerializer.java

@SuppressWarnings("unchecked")
void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) {
    Object param = null;/*from   www .  j ava 2 s .c  o  m*/
    Throwable ex = null;
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        if (m.getName().equals(name)) {
            Class<?>[] paramTypes = m.getParameterTypes();
            if (paramTypes.length == 1 && jo.has(key)) {
                Class<?> tparam = paramTypes[0];
                boolean allowNull = false;
                try {
                    if (jo.isNull(key)) {
                        // do nothing because param is already null : lets us not null on other types
                    } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) {
                        param = new Long(jo.getLong(key));
                    } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) {
                        param = new Double(jo.getDouble(key));
                    } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) {
                        param = new Integer(jo.getInt(key));
                    } else if (String.class.isAssignableFrom(tparam)) {
                        param = jo.getString(key);
                    } else if (Enum.class.isAssignableFrom(tparam)) {
                        param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key));
                    } else if (Boolean.class.isAssignableFrom(tparam)) {
                        param = new Boolean(jo.getBoolean(key));
                    } else if (jo.isNull(key)) {
                        param = null;
                        allowNull = true;
                    } else if (Collection.class.isAssignableFrom(tparam)) {

                        if (m.getGenericParameterTypes().length > 0) {
                            Type t = m.getGenericParameterTypes()[0];
                            if (t instanceof ParameterizedType) {
                                ParameterizedType tv = (ParameterizedType) t;
                                if (tv.getActualTypeArguments().length > 0
                                        && tv.getActualTypeArguments()[0] == String.class) {

                                    List<String> ls = new ArrayList<String>();
                                    JSONArray ja = jo.optJSONArray(key);
                                    if (ja != null) {
                                        for (int j = 0; j < ja.length(); j++) {
                                            ls.add(ja.getString(j));
                                        }
                                    }
                                    param = ls;
                                } else if (tv.getActualTypeArguments().length == 1) {
                                    ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0];
                                    Class itemClass = (Class) type.getRawType();
                                    if (itemClass == Map.class && type.getActualTypeArguments().length == 2
                                            && type.getActualTypeArguments()[0] == String.class
                                            && type.getActualTypeArguments()[1] == Object.class) {

                                        List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();

                                        JSONArray ja = jo.optJSONArray(key);
                                        if (ja != null) {
                                            for (int j = 0; j < ja.length(); j++) {
                                                Map<String, Object> map = new HashMap<String, Object>();
                                                JSONObject mo = ja.getJSONObject(j);
                                                Iterator<String> keys = mo.keys();
                                                while (keys.hasNext()) {
                                                    String okey = keys.next();
                                                    Object ovalue = null;
                                                    // make sure we don't get JSONObject$Null
                                                    if (!mo.isNull(okey)) {
                                                        ovalue = mo.get(okey);
                                                    }
                                                    map.put(okey, ovalue);
                                                }
                                                ls.add(map);
                                            }
                                        }
                                        param = ls;
                                    } else {
                                        getLogger().warning(
                                                "Don't know how to handle Collection of type : " + itemClass);
                                    }

                                } else {
                                    getLogger().warning("Don't know how to handle Collection of type : "
                                            + tv.getActualTypeArguments()[0]);
                                }
                            }
                        }
                    } else {
                        getLogger().warning(
                                "Unable to serialize " + key + " :  Don't know how to handle " + tparam);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (param != null || allowNull) {

                    try {

                        if (m != null) {
                            Object[] args = { param };
                            m.invoke(targetObject, args);
                            ex = null;
                            break;
                        }
                    } catch (SecurityException e) {
                        ex = e;
                    } catch (IllegalArgumentException e) {
                        ex = e;
                    } catch (IllegalAccessException e) {
                        ex = e;
                    } catch (InvocationTargetException e) {
                        ex = e;
                    }
                }
            }
        }
    }
    if (ex != null) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException(ex);
        }
    }
}

From source file:org.hyperledger.common.Base58Test.java

@Test
public void base58encode() throws IOException, JSONException, HyperLedgerException {
    JSONArray testData = readObjectArray(BASE58_ENCODE);
    for (int i = 0; i < testData.length(); ++i) {
        JSONArray test = testData.getJSONArray(i);
        assertTrue(ByteUtils.toBase58(ByteUtils.fromHex(test.getString(0))).equals(test.get(1)));
        assertTrue(ByteUtils.toHex(ByteUtils.fromBase58(test.getString(1))).equals(test.get(0)));
    }/*  w  w  w  .  ja v  a  2s . c  om*/
}

From source file:de.rwthaachen.rz.rwthapp.plugins.fileopener.FileOpener.java

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {

    try {/*w  w w  .  j  av  a 2 s . c o m*/
        if (action.equals("openFile")) {
            if (openFile(args.getString(0))) {
                callbackContext.success();
            } else {
                callbackContext.error("Could not open file");
            }
            return true;
        }
    } catch (IOException e) {
        e.printStackTrace();
        callbackContext.error(e.getMessage());
    } catch (RuntimeException e) { // KLUDGE for Activity Not Found
        e.printStackTrace();
        callbackContext.error(e.getMessage());
    }
    return false;
}

From source file:com.knurld.dropboxdemo.KnurldActivity.java

public void recordEnrollment(View view) {
    Intent intent = new Intent(this, RecordWAVActivity.class);
    JSONArray vocabArray = knurldService.getAppModel().getVocabulary();
    String vocab = "";
    for (int i = 0; i < vocabArray.length(); i++) {
        try {/*from w ww .  ja  va 2s  .  co m*/
            vocab += vocabArray.getString(i) + " ";
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    intent.putExtra(KNURLD_INSTRUCTIONS, vocab);

    startActivity(intent);
}