Example usage for org.json JSONArray optJSONObject

List of usage examples for org.json JSONArray optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(int index) 

Source Link

Document

Get the optional JSONObject associated with an index.

Usage

From source file:org.apache.cordova.navigationmenu.NavigationMenu.java

/**
 * Displays popup menu./*from   w w  w  .  ja  v a2s  .  co m*/
 *
 * @param items   The array of objects which describes menu items.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void showPopup(JSONArray items) {
    final PopupMenu popup = new PopupMenu(this.webView.getContext(), this.webView);

    PopupMenu.OnMenuItemClickListener handler = new PopupMenu.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            int itemId = item.getItemId();
            webView.sendJavascript("menu.popupItemClick && menu.popupItemClick(" + itemId + ");");
            return false;
        }
    };
    popup.setOnMenuItemClickListener(handler);
    Menu popupMenu = popup.getMenu();
    for (int i = 0; i < items.length(); i++) {
        JSONObject menuItem = items.optJSONObject(i);
        if (menuItem != null) {
            appendItem(popupMenu, menuItem);
        }
    }

    this.cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {
            popup.show();
        }
    });

}

From source file:com.sina.weibo.sdk_lib.openapi.models.FavoriteList.java

public static FavoriteList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }//  ww w .j  a  v a  2s .  c  om

    FavoriteList favorites = new FavoriteList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        favorites.total_number = jsonObject.optInt("total_number", 0);

        JSONArray jsonArray = jsonObject.optJSONArray("favorites");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            favorites.favoriteList = new ArrayList<Favorite>(length);
            for (int ix = 0; ix < length; ix++) {
                favorites.favoriteList.add(Favorite.parse(jsonArray.optJSONObject(ix)));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return favorites;
}

From source file:com.futureplatforms.kirin.extensions.localnotifications.LocalNotificationsBackend.java

@Override
public void scheduleNotifications_(JSONArray notifications) {
    AlarmManager am = (AlarmManager) mContext.getSystemService(Service.ALARM_SERVICE);

    Editor prefs = mPrefs.edit();/*from  w ww . j  a  v a 2s.  c om*/
    for (int i = 0, max = notifications.length(); i < max; i++) {
        JSONObject obj = notifications.optJSONObject(i);
        if (scheduleSingleNotification(am, obj)) {
            prefs.putString(PREFS_PREFIX + obj.optInt("id"), obj.toString());
        }
    }
    prefs.commit();

}

From source file:com.ammobyte.radioreddit.api.GetSongInfo.java

@Override
protected Boolean doInBackground(String... params) {
    final String cookie = params[0]; // This will be null if not logged in

    // Prepare GET with cookie, execute it, parse response as JSON
    JSONObject response = null;//  w w w .  ja v a2s  .c o m
    try {
        final HttpClient httpClient = new DefaultHttpClient();
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("url", mSong.reddit_url));
        final HttpGet httpGet = new HttpGet(
                "http://www.reddit.com/api/info.json?" + URLEncodedUtils.format(nameValuePairs, "utf-8"));
        if (cookie != null) {
            // Using HttpContext, CookieStore, and friends didn't work
            httpGet.setHeader("Cookie", "reddit_session=" + cookie);
        }
        httpGet.setHeader("User-Agent", RedditApi.USER_AGENT);
        final HttpResponse httpResponse = httpClient.execute(httpGet);
        response = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while getting song info", e);
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while getting song info", e);
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while getting song info", e);
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while getting song info", e);
    } catch (JSONException e) {
        Log.i(RedditApi.TAG, "JSONException while getting song info", e);
    }

    // Check for failure
    if (response == null) {
        Log.i(RedditApi.TAG, "Response is null");
        return false;
    }

    // Get the info we want
    final JSONObject data1 = response.optJSONObject("data");
    if (data1 == null) {
        Log.i(RedditApi.TAG, "First data is null");
        return false;
    }
    final String modhash = data1.optString("modhash", "");
    if (modhash.length() > 0) {
        mService.setModhash(modhash);
    }
    final JSONArray children = data1.optJSONArray("children");
    if (children == null) {
        Log.i(RedditApi.TAG, "Children is null");
        return false;
    }
    final JSONObject child = children.optJSONObject(0);
    if (child == null) {
        // This is common if the song hasn't been submitted to reddit yet
        // so we intentionally don't log this case
        return false;
    }
    final String kind = child.optString("kind");
    if (kind == null) {
        Log.i(RedditApi.TAG, "Kind is null");
        return false;
    }
    final JSONObject data2 = child.optJSONObject("data");
    if (data2 == null) {
        Log.i(RedditApi.TAG, "Second data is null");
        return false;
    }
    final String id = data2.optString("id");
    if (id == null) {
        Log.i(RedditApi.TAG, "Id is null");
        return false;
    }
    final int score = data2.optInt("score");
    Boolean likes = null;
    if (!data2.isNull("likes")) {
        likes = data2.optBoolean("likes");
    }
    final boolean saved = data2.optBoolean("saved");

    // Modify song with collected info
    if (kind != null && id != null) {
        mSong.reddit_id = kind + "_" + id;
    } else {
        mSong.reddit_id = null;
    }
    mSong.upvoted = (likes != null && likes == true);
    mSong.downvoted = (likes != null && likes == false);
    mSong.votes = score;
    mSong.saved = saved;

    return true;
}

From source file:com.facebook.internal.Utility.java

private static Map<String, Map<String, DialogFeatureConfig>> parseDialogConfigurations(
        JSONObject dialogConfigResponse) {
    HashMap<String, Map<String, DialogFeatureConfig>> dialogConfigMap = new HashMap<String, Map<String, DialogFeatureConfig>>();

    if (dialogConfigResponse != null) {
        JSONArray dialogConfigData = dialogConfigResponse.optJSONArray("data");
        if (dialogConfigData != null) {
            for (int i = 0; i < dialogConfigData.length(); i++) {
                DialogFeatureConfig dialogConfig = DialogFeatureConfig
                        .parseDialogConfig(dialogConfigData.optJSONObject(i));
                if (dialogConfig == null) {
                    continue;
                }/*from  w  ww.j  a  v a  2 s .c om*/

                String dialogName = dialogConfig.getDialogName();
                Map<String, DialogFeatureConfig> featureMap = dialogConfigMap.get(dialogName);
                if (featureMap == null) {
                    featureMap = new HashMap<String, DialogFeatureConfig>();
                    dialogConfigMap.put(dialogName, featureMap);
                }
                featureMap.put(dialogConfig.getFeatureName(), dialogConfig);
            }
        }
    }

    return dialogConfigMap;
}

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

private void createActionBar(final JSONArray jsonTabs) {
    Log.vc(VERBOSE, TAG, "createActionBar: jsonTabs=" + jsonTabs);

    final ActionBar actionBar = getSupportActionBar();
    actionBar.removeAllTabs();//w  w w . j a va  2  s .  c  o m

    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setDisplayShowTitleEnabled(false);

    ActionBar.TabListener tabListener = new XTabListener(viewPager);

    // Add the button tabs to the ActionBar.
    int i;
    for (i = 0; i < jsonTabs.length(); i++) {
        JSONObject jsonTab = jsonTabs.optJSONObject(i);
        if (jsonTab == null) {
            continue;
        }

        final String name = jsonTab.optString(JsonSpec.TAB_NAME, JsonSpec.DEFAULT_TAB_NAME);

        actionBar.addTab(actionBar.newTab().setText(name).setTabListener(tabListener));
    }

    // Add the special tabs to the ActionBar.
    actionBar.addTab(actionBar.newTab().setText(getString(R.string.summary)).setTabListener(tabListener));
    i++;
    actionBar.addTab(actionBar.newTab().setText(getString(R.string.history)).setTabListener(tabListener));
    i++;
}

From source file:org.marietjedroid.connect.MarietjeClient.java

/**
 * Gets the queue Blocks until we have it
 * /*  w w w . ja v a2  s .com*/
 * @return
 * @throws MarietjeException
 */
public MarietjeTrack[] getQueue() throws MarietjeException {
    if (channel.getException() != null)
        throw channel.getException();

    ArrayList<MarietjeRequest> queue = new ArrayList<MarietjeRequest>();

    try {
        if (!this.followingQueue || this.channel.getRequests() == null) {
            this.followQueue();
            this.requestsRetrieved.acquire();

        }

        JSONArray requests = this.channel.getRequests();

        for (int i = 0; requests.optJSONObject(i) != null; i++) {
            JSONObject req = requests.getJSONObject(i);
            JSONObject media = req.getJSONObject("media");
            String requester = req.optString("byKey", DEFAULT_REQUESTER);
            queue.add(new MarietjeRequest(requester, req.getInt("key"), media));
        }

    } catch (JSONException e) {
        throw new MarietjeException("JSON Error");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return queue.toArray(new MarietjeTrack[0]);
}

From source file:net.redwarp.android.app.githubcount.ProjectDetailFragment.java

private void parseReleases(JSONArray jsonArray) {
    List<Release> releases = new ArrayList<>(jsonArray.length());
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject object = jsonArray.optJSONObject(i);
        Release release = new Release(object);
        releases.add(release);//w w w .j a  va  2 s  .com
    }

    mListView.setAdapter(new ReleaseAdapter(releases));
    for (int i = 0; i < releases.size(); i++) {
        mListView.expandGroup(i);
    }
}

From source file:org.jjdltc.cordova.plugin.sftp.JJsftp.java

/**
 * Validate if the options sent by user are not null or empty and also if accomplish the base structure
 * //from   w  w w. j  ava2  s.  c o  m
 * @param arguments         The arguments passed by user with the JSONObject that has the host options
 * @return                  A valid 'hostData' JSONObject with its inner host options to connect
 * @throws JSONException
 */
private JSONObject setHostData(JSONArray arguments) throws JSONException {
    JSONObject hostData = arguments.optJSONObject(0);
    boolean validArgs = true;
    String[] keys = new String[] { "host", "user", "pswd" };

    if (hostData == null) {
        return null;
    }
    if (hostData.opt("port") == null) {
        hostData.put("port", 22);
    }

    for (int i = 0; i < keys.length; i++) {
        if (hostData.opt(keys[i]) == null) {
            validArgs = false;
            break;
        }
    }

    return (validArgs) ? hostData : null;
}

From source file:org.jjdltc.cordova.plugin.sftp.JJsftp.java

/**
 * Validate if the options sent by user are not null or empty and also if accomplish the base structure
 * /*from   ww w. j av a  2  s . c o  m*/
 * @param arguments         The arguments passed by user with the JSONArray of JSONObject with the local and remote path of the files
 * @return                  A valid 'actionArr' JSONArray with its inner JSONObject paths
 */
private JSONArray setActionArr(JSONArray arguments) {
    JSONArray actionArr = arguments.optJSONArray(1);
    boolean validArr = true;

    if (actionArr == null) {
        return null;
    }

    for (int i = 0; i < actionArr.length(); i++) {
        JSONObject tempActionObj = actionArr.optJSONObject(i);
        if (tempActionObj == null) {
            validArr = false;
        } else {
            validArr = (tempActionObj.opt("remote") == null || tempActionObj.opt("local") == null) ? false
                    : validArr;
        }
        if (!validArr) {
            break;
        }
    }

    return (validArr) ? actionArr : null;
}