Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

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));
                    }//from   www . j a  va 2s .  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) {
            }
        }
    }
}

From source file:com.snappy.couchdb.CouchDBHelper.java

/**
 * Parses multi notification objects/*from   w  w  w  . j a v  a 2 s.  co m*/
 * 
 * @param notificationsJson
 * @return
 * @throws SpikaException 
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public static List<Notification> parseMultiNotificationObjects(JSONArray notificationsAry)
        throws ClientProtocolException, IOException, SpikaException {

    List<Notification> notifications = new ArrayList<Notification>();

    for (int i = 0; i < notificationsAry.length(); i++) {

        try {
            JSONObject notificationJson = (JSONObject) notificationsAry.get(i);
            Notification notification = new Notification();
            notification = sGsonExpose.fromJson(notificationJson.toString(), Notification.class);

            if (notificationJson.has(Const.MESSAGES)) {
                JSONArray messagesAry = notificationJson.getJSONArray(Const.MESSAGES);
                notification.setMessages(
                        parseMultiNotificationMessageObjects(messagesAry, notification.getTargetId()));
            }

            notifications.add(notification);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return notifications;
}

From source file:com.snappy.couchdb.CouchDBHelper.java

/**
 * Parses multi notification message objects
 * /*from   w  w  w .ja  v a  2s . c o  m*/
 * @param messagesJson
 * @return
 * @throws SpikaException 
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public static List<NotificationMessage> parseMultiNotificationMessageObjects(JSONArray messagesArray,
        String targetId) throws ClientProtocolException, IOException, SpikaException {

    List<NotificationMessage> messages = new ArrayList<NotificationMessage>();

    for (int i = 0; i < messagesArray.length(); i++) {
        try {
            JSONObject messageJson = (JSONObject) messagesArray.get(i);
            NotificationMessage notificationMessage = new NotificationMessage();
            notificationMessage = sGsonExpose.fromJson(messageJson.toString(), NotificationMessage.class);
            notificationMessage.setTargetId(targetId);
            //            notificationMessage.setUserAvatarFileId(CouchDB
            //                  .findAvatarFileId(notificationMessage.getFromUserId()));
            messages.add(notificationMessage);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return messages;
}

From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java

private static Object getCoinValueBTC() {
    Date date = new Date();
    long now = date.getTime();

    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;/*from  w w  w  . jav  a2  s  .c o m*/
    String currencyCryptsy = CoinDefinition.cryptsyMarketCurrency;
    String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid="
            + CoinDefinition.cryptsyMarketId;

    HttpURLConnection connectionCryptsy = null;
    try {
        // final String currencyCode = currencies[i];
        final URL URLCryptsy = new URL(urlCryptsy);
        connectionCryptsy = (HttpURLConnection) URLCryptsy.openConnection();
        connectionCryptsy.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.connect();

        final StringBuilder contentCryptsy = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024));
            Io.copy(reader, contentCryptsy);
            final JSONObject head = new JSONObject(contentCryptsy.toString());
            JSONObject returnObject = head.getJSONObject("return");
            JSONObject markets = returnObject.getJSONObject("markets");
            JSONObject coinInfo = markets.getJSONObject(CoinDefinition.coinTicker);

            JSONArray recenttrades = coinInfo.getJSONArray("recenttrades");

            double btcTraded = 0.0;
            double coinTraded = 0.0;

            for (int i = 0; i < recenttrades.length(); ++i) {
                JSONObject trade = (JSONObject) recenttrades.get(i);

                btcTraded += trade.getDouble("total");
                coinTraded += trade.getDouble("quantity");

            }

            Double averageTrade = btcTraded / coinTraded;

            //Double lastTrade = GLD.getDouble("lasttradeprice");

            //String euros = String.format("%.7f", averageTrade);
            // Fix things like 3,1250
            //euros = euros.replace(",", ".");
            //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost()));
            if (currencyCryptsy.equalsIgnoreCase("BTC"))
                btcRate = averageTrade;

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException x) {
                    // swallow
                }
            }
        }
        return btcRate;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    } finally {
        if (connectionCryptsy != null)
            connectionCryptsy.disconnect();
    }

    return null;
}

From source file:com.groupon.odo.proxylib.OverrideService.java

/**
 * This only gets half of the EnabledEndpoint from a JDBC ResultSet
 * Getting the method for the override id requires an additional SQL query and needs to be called after
 * the SQL connection is released//  w ww.j a  va2  s  .c o m
 *
 * @param result result to scan for endpoint
 * @return EnabledEndpoint
 * @throws Exception exception
 */
private EnabledEndpoint getPartialEnabledEndpointFromResultset(ResultSet result) throws Exception {
    EnabledEndpoint endpoint = new EnabledEndpoint();
    endpoint.setId(result.getInt(Constants.GENERIC_ID));
    endpoint.setPathId(result.getInt(Constants.ENABLED_OVERRIDES_PATH_ID));
    endpoint.setOverrideId(result.getInt(Constants.ENABLED_OVERRIDES_OVERRIDE_ID));
    endpoint.setPriority(result.getInt(Constants.ENABLED_OVERRIDES_PRIORITY));
    endpoint.setRepeatNumber(result.getInt(Constants.ENABLED_OVERRIDES_REPEAT_NUMBER));

    ArrayList<Object> args = new ArrayList<Object>();
    try {
        JSONArray arr = new JSONArray(result.getString(Constants.ENABLED_OVERRIDES_ARGUMENTS));
        for (int x = 0; x < arr.length(); x++) {
            args.add(arr.get(x));
        }
    } catch (Exception e) {
        // ignore it.. this means the entry was null/corrupt
    }

    endpoint.setArguments(args.toArray(new Object[0]));

    return endpoint;
}

From source file:cn.suishen.email.Preferences.java

HashSet<String> parseEmailSet(String serialized) throws JSONException {
    HashSet<String> result = new HashSet<String>();
    if (!TextUtils.isEmpty(serialized)) {
        JSONArray arr = new JSONArray(serialized);
        for (int i = 0, len = arr.length(); i < len; i++) {
            result.add((String) arr.get(i));
        }/*from   ww w .j av a  2s . c om*/
    }
    return result;
}

From source file:com.melniqw.instagramsdk.Media.java

public static Media fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Media media = new Media();
    media.id = o.optString("id");
    media.type = o.optString("type");
    media.createdTime = o.optString("created_time");
    media.attribution = o.optString("attribution");
    media.image = Image.fromJSON(o.optJSONObject("images"));
    if (media.type.equals("video"))
        media.video = Video.fromJSON(o.optJSONObject("videos"));
    media.link = o.optString("link");
    media.filter = o.optString("filter");
    media.userHasLiked = o.optBoolean("user_has_liked");
    media.user = User.fromJSON(o.optJSONObject("user"));
    JSONArray tagsJSONArray = o.optJSONArray("tags");
    ArrayList<String> tags = new ArrayList<>();
    for (int j = 0; j < tagsJSONArray.length(); j++) {
        tags.add(tagsJSONArray.optString(j));
    }//  ww w  . j  a v  a 2  s  .  c  o m
    media.tags.addAll(tags);
    JSONArray likesJSONArray = o.optJSONObject("likes").optJSONArray("data");
    ArrayList<Like> likes = new ArrayList<>();
    for (int j = 0; j < likesJSONArray.length(); j++) {
        JSONObject likeJSON = (JSONObject) likesJSONArray.get(j);
        likes.add(Like.fromJSON(likeJSON));
    }
    media.likes.addAll(likes);
    JSONArray commentJSONArray = o.optJSONObject("comments").optJSONArray("data");
    ArrayList<Comment> comments = new ArrayList<>();
    for (int j = 0; j < commentJSONArray.length(); j++) {
        JSONObject commentJSON = (JSONObject) commentJSONArray.get(j);
        comments.add(Comment.fromJSON(commentJSON));
    }
    media.comments.addAll(comments);
    JSONArray usersInPhotoJSON = o.optJSONArray("users_in_photo");
    ArrayList<UserInPhoto> usersInPhotos = new ArrayList<>();
    for (int j = 0; j < usersInPhotoJSON.length(); j++) {
        JSONObject userInPhotoJSON = (JSONObject) usersInPhotoJSON.get(j);
        usersInPhotos.add(UserInPhoto.fromJSON(userInPhotoJSON));
    }
    media.usersInPhoto.addAll(usersInPhotos);
    JSONObject locationJSON = o.optJSONObject("location");
    if (locationJSON != null) {
        media.location = Location.fromJSON(locationJSON);
    }
    JSONObject captionJSON = o.optJSONObject("caption");
    if (captionJSON != null) {
        media.caption = Comment.fromJSON(captionJSON);
    }
    return media;
}

From source file:org.mixare.data.convert.GeoDataProcessorGeoJSON.java

@Override
public List<Marker> load(String rawData, int taskId, int colour) throws JSONException {
    String id = "";
    String title = "";
    String description = ""; //not used by Mixare
    String URL = "";
    String meaning = ""; //not used by Mixare
    JSONObject geometry = null;/*from ww w  .ja  v  a2  s. c  om*/
    String type = ""; //not used by Mixare
    JSONArray coordinates = null;
    double lat = 0, lng = 0;

    List<Marker> markers = new ArrayList<Marker>();
    JSONObject root = convertToJSON(rawData);
    Log.v("root", root.toString());
    JSONArray dataArray = root.getJSONArray("features");
    int top = Math.min(MAX_JSON_OBJECTS, dataArray.length());

    Marker ma = null;

    for (int i = 0; i < top; i++) {
        JSONObject object = dataArray.getJSONObject(i);
        JSONObject properties = object.getJSONObject("properties");

        if (properties.has("obj_id")) {
            id = properties.getString("obj_id");
        }

        if (properties.has("title")) {
            title = properties.getString("title");
        }

        if (properties.has("description")) {
            description = properties.getString("description");
        }

        if (properties.has("URL")) {
            URL = properties.getString("URL");
        }

        if (properties.has("meaning")) {
            meaning = properties.getString("meaning");
        }

        geometry = object.getJSONObject("geometry");

        if (geometry.has("type")) {
            type = geometry.getString("type");
        }

        if (geometry.has("coordinates")) {
            coordinates = geometry.getJSONArray("coordinates");
        }

        if (type.equals("Point")) {

            lat = (Double) coordinates.get(0);
            lng = (Double) coordinates.get(1);

            ma = new POIMarker(id, HtmlUnescape.unescapeHTML(title), meaning, lat, lng, 0, // elevation to be implemented, 
                    URL, taskId, colour);

            markers.add(ma);
        }

        if (type.equals("MultiPoint")) {
            int length = coordinates.length();
            for (int j = 0; j < length; j++) {
                JSONArray sub_coordinates = coordinates.getJSONArray(j);
                lat = (Double) sub_coordinates.get(0);
                lng = (Double) sub_coordinates.get(1);

                ma = new POIMarker(id, HtmlUnescape.unescapeHTML(title), meaning, lat, lng, 0, // elevation to be implemented, 
                        URL, taskId, colour);

                markers.add(ma);
            }
        }
    }

    return markers;
}

From source file:com.tobolkac.triviaapp.ScreenSlideActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_screen_slide);
    Bundle b = getIntent().getExtras();/*w ww .  j  a v a  2  s  . c  o m*/
    Parse.initialize(this, "paHnFob0MGoBuy16Pzg5YPCH6TMOZfgZPXEOY1em",
            "1WOoBPDmOAu9CbHfvKIGmNIt2mY32mEvBYoLcPLV");
    ParseAnalytics.trackAppOpened(getIntent());
    //        questionNums = b.getIntArray("questionsNumArray");
    //        cat = b.getString("category");
    timerTextView = (TextView) findViewById(R.id.gameTimer);
    timerTextView.setText("2:00");
    cdt.start();

    //set up vibrator
    vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    //Challenging (Creating Game)
    if (b.getString("com.parse.Data") == null && b.getString("gameId") == null) {
        isChallenger = true;
        //          userList.setText("Challenging");
        challengedUser = getIntent().getStringExtra("opponentName");
        cat = b.getString("category");
        Log.d("category", "category: " + cat);
        questionNums = getIntent().getIntegerArrayListExtra("questionNumArray");

        //query to batch retrieve questions
        ParseQuery<ParseObject> queryQuestions = ParseQuery.getQuery("Questions");
        queryQuestions.whereEqualTo("category", cat);
        queryQuestions.whereContainedIn("categoryIndex", questionNums);
        /*queryQuestions.findInBackground(new FindCallback<ParseObject>() {
                
        @Override
        public void done(List<ParseObject> objects, ParseException e) {
          Log.d("questions retrieved", "number: " + objects.size());
          questions = objects;
        }
        });*/

        correctArray = new int[questionNums.size()];
        for (int i = 0; i < correctArray.length; i++) {
            correctArray[i] = 0;
        }
        try {
            questions = queryQuestions.find();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.d("questionNums after",
                "In ScrrenSlideActivity: " + questionNums.toString() + " " + questions.size());

    } else {
        //Being Challenged (From Homescreen)
        if (b.getString("gameId") != null) {
            gameId = b.getString("gameId");
        } else {
            try {
                JSONObject data = new JSONObject(b.getString("com.parse.Data"));
                gameId = data.getString("gameId");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        isChallenger = false;

        ParseQuery<ParseObject> query = ParseQuery.getQuery("Games");
        try {
            ParseObject gameObj = query.get(gameId);
            challenger = gameObj.getString("challenger");
            opponent = gameObj.getString("opponent");
            cat = gameObj.getString("category");
            //getting question array from game object
            JSONArray q = gameObj.getJSONArray("questionsArray");
            Log.d("Json array", "length: " + q.length());
            ArrayList<Integer> stuff = new ArrayList<Integer>();
            for (int s = 0; s < q.length(); s++) {
                stuff.add((Integer) q.get(s));
            }

            Log.d("opponent questions Array", stuff.toString());

            //query to grab questions by category and number
            ParseQuery<ParseObject> queryQuestions = ParseQuery.getQuery("Questions");
            queryQuestions.whereEqualTo("category", cat);
            queryQuestions.whereContainedIn("categoryIndex", stuff);

            correctArray = new int[stuff.size()];
            for (int i = 0; i < correctArray.length; i++) {
                correctArray[i] = 0;
            }
            try {
                questions = queryQuestions.find();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    // Instantiate a ViewPager and a PagerAdapter.
    mPager = (ViewPager) findViewById(R.id.pager);
    FragmentManager manager = getSupportFragmentManager();
    mPagerAdapter = new ScreenSlidePagerAdapter(manager);
    mPager.setAdapter(mPagerAdapter);
    mPager.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            return true;
        }
    });
    mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            // When changing pages, reset the action bar actions since they are dependent
            // on which page is currently active. An alternative approach is to have each
            // fragment expose actions itself (rather than the activity exposing actions),
            // but for simplicity, the activity provides the actions in this sample.

            questionProgress.setCorrectArray(correctArray);
            questionProgress.setNumCorrect(position + 1);

            invalidateOptionsMenu();
        }
    });

    timerTextView = (TextView) findViewById(R.id.gameTimer);
    startTime = System.currentTimeMillis();

    questionProgress = ((CorrectQuestionView) findViewById(R.id.questionProgress));
    questionProgress.setQuestionProgress(true);
    questionProgress.setNumCorrect(1);
    questionProgress.setCorrectArray(correctArray);

}

From source file:nz.co.wholemeal.christchurchmetro.FavouritesActivity.java

private void initFavourites() {
    SharedPreferences favourites = getSharedPreferences(PlatformActivity.PREFERENCES_FILE, 0);
    String stops_json = favourites.getString("favouriteStops", null);

    if (stops_json != null) {
        Log.d(TAG, "initFavourites(): stops_json = " + stops_json);
        try {/*  w w w.  ja  va  2  s .  co m*/
            ArrayList favouriteStops = new ArrayList<Stop>();
            JSONArray stopsArray = (JSONArray) new JSONTokener(stops_json).nextValue();

            for (int i = 0; i < stopsArray.length(); i++) {
                try {
                    String platformTag = (String) stopsArray.get(i);
                    Log.d(TAG, "Loading stop platformTag = " + platformTag);
                    Stop stop = new Stop(platformTag, null, getApplicationContext());
                    favouriteStops.add(stop);
                    Log.d(TAG, "initFavourites(): added stop platformTag = " + stop.platformTag);
                } catch (Stop.InvalidPlatformNumberException e) {
                    Log.e(TAG, "Invalid platformTag in favourites: " + e.getMessage());
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException() parsing favourites: " + e.getMessage());
                }
            }

            if (favouriteStops.size() > 0) {
                stops.addAll(favouriteStops);
            }
        } catch (JSONException e) {
            Log.e(TAG, "initFavourites(): JSONException: " + e.toString());
        }
    }
}