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.yozio.demo.implementations.twitter.ListFollowersActivity.java

@Override
public void executeDemo(String text) {

    TwitterUtils.link(this, new SocializeAuthListener() {

        @Override//from w  w w.ja v  a2s .  c o  m
        public void onError(SocializeException error) {
            handleError(ListFollowersActivity.this, error);
        }

        @Override
        public void onCancel() {
            handleCancel();
        }

        @Override
        public void onAuthSuccess(SocializeSession session) {

            TwitterUtils.get(ListFollowersActivity.this, "followers/ids.json", null,
                    new SocialNetworkPostListener() {

                        @Override
                        public void onNetworkError(Activity context, SocialNetwork network, Exception error) {
                            handleError(context, error);
                        }

                        @Override
                        public void onCancel() {
                            handleCancel();
                        }

                        @Override
                        public void onAfterPost(Activity parent, SocialNetwork socialNetwork,
                                JSONObject responseObject) {

                            try {
                                JSONArray jsonArray = responseObject.getJSONArray("ids");

                                StringBuilder builder = new StringBuilder();

                                int len = jsonArray.length();

                                for (int i = 0; i < len; i++) {
                                    if (i > 0) {
                                        builder.append("\n");
                                    }
                                    builder.append(jsonArray.getString(i));
                                }

                                handleResult(builder.toString());
                            } catch (JSONException e) {
                                handleError(parent, e);
                            }
                        }
                    });
        }

        @Override
        public void onAuthFail(SocializeException error) {
            handleError(ListFollowersActivity.this, error);
        }
    });
}

From source file:com.malmstein.androidtvexplorer.video.VideoProvider.java

public static HashMap<String, List<Video>> buildMedia(String url) throws JSONException {
    if (null != mMovieList) {
        return mMovieList;
    }/* w ww.ja  va2s.c o  m*/
    mMovieList = new HashMap<String, List<Video>>();

    JSONObject jsonObj = new VideoProvider().parseUrl(url);
    JSONArray categories = jsonObj.getJSONArray(TAG_GOOGLE_VIDEOS);
    if (null != categories) {
        Log.d(TAG, "category #: " + categories.length());
        String title;
        String videoUrl;
        String bgImageUrl;
        String cardImageUrl;
        String studio;
        for (int i = 0; i < categories.length(); i++) {
            JSONObject category = categories.getJSONObject(i);
            String category_name = category.getString(TAG_CATEGORY);
            JSONArray videos = category.getJSONArray(TAG_MEDIA);
            Log.d(TAG, "category: " + i + " Name:" + category_name + " video length: " + videos.length());
            List<Video> categoryList = new ArrayList<Video>();
            if (null != videos) {
                for (int j = 0; j < videos.length(); j++) {
                    JSONObject video = videos.getJSONObject(j);
                    String description = video.getString(TAG_DESCRIPTION);
                    JSONArray videoUrls = video.getJSONArray(TAG_SOURCES);
                    if (null == videoUrls || videoUrls.length() == 0) {
                        continue;
                    }
                    title = video.getString(TAG_TITLE);
                    videoUrl = getVideoPrefix(category_name, videoUrls.getString(0));
                    bgImageUrl = getThumbPrefix(category_name, title, video.getString(TAG_BACKGROUND));
                    cardImageUrl = getThumbPrefix(category_name, title, video.getString(TAG_CARD_THUMB));
                    studio = video.getString(TAG_STUDIO);
                    categoryList.add(buildMovieInfo(category_name, title, description, studio, videoUrl,
                            cardImageUrl, bgImageUrl));
                }
                mMovieList.put(category_name, categoryList);
            }
        }
    }
    return mMovieList;
}

From source file:org.dasein.persist.riak.RiakCache.java

public void reindex() {
    JSONObject ob;//w w w.j a v a  2  s  .  c  o m

    try {
        ob = findKeysInBucketAsJSON();
    } catch (PersistenceException e) {
        std.warn("Unable to re-index: " + e.getMessage(), e);
        return;
    }
    if (ob.has("keys")) {
        try {
            JSONArray keys = ob.getJSONArray("keys");

            for (int i = 0; i < keys.length(); i++) {
                String key = keys.getString(i);
                try {
                    T item = get(key);

                    if (item != null) {
                        reindex(item);
                    }
                } catch (Throwable t) {
                    std.warn("Unable to re-index: " + t.getMessage(), t);
                }
            }
        } catch (Throwable t) {
            std.warn("Unable to re-index: " + t.getMessage(), t);
        }
    }
}

From source file:org.dasein.persist.riak.RiakCache.java

private @Nonnull Iterable<T> list(boolean asCursor, @Nonnull String listEndpoint,
        final @Nullable JiteratorFilter<T> filter) throws PersistenceException {
    if (std.isTraceEnabled()) {
        std.trace("ENTER: " + RiakCache.class.getName() + ".list(" + listEndpoint + ")");
    }//from www.  ja v  a 2 s . c om
    try {
        startCall("list");
        try {
            HttpClient client = getClient();
            GetMethod get = new GetMethod(listEndpoint);
            int code;

            if (wire.isDebugEnabled()) {
                try {
                    wire.debug(get.getName() + " " + listEndpoint);
                    wire.debug("");
                    for (Header h : get.getRequestHeaders()) {
                        wire.debug(h.getName() + ": " + h.getValue());
                    }
                    wire.debug("");
                } catch (Throwable ignore) {
                    // ignore
                }
            }
            try {
                code = client.executeMethod(get);
            } catch (HttpException e) {
                throw new PersistenceException("HttpException during GET: " + e.getMessage());
            } catch (IOException e) {
                throw new PersistenceException("IOException during GET: " + e.getMessage());
            }
            try {
                final String body = get.getResponseBodyAsString();

                try {
                    if (wire.isDebugEnabled()) {
                        wire.debug("----------------------------------------");
                        wire.debug("");
                        wire.debug(get.getStatusLine().getStatusCode() + " "
                                + get.getStatusLine().getReasonPhrase());
                        wire.debug("");
                        if (body != null) {
                            wire.debug(body);
                            wire.debug("");
                        }
                    }
                } catch (Throwable ignore) {
                    // ignore
                }
                if (code != HttpStatus.SC_OK) {
                    if (code == HttpStatus.SC_NOT_FOUND) {
                        return Collections.emptyList();
                    }
                    throw new PersistenceException(code + ": " + body);
                }
                JSONObject ob = new JSONObject(body);

                if (ob.has("keys")) {
                    final JSONArray keys = ob.getJSONArray("keys");
                    final int len = keys.length();

                    if (asCursor) {
                        CursorPopulator<T> populator = new CursorPopulator<T>(getTarget().getName() + ".list",
                                null) {
                            @Override
                            public void populate(ForwardCursor<T> cursor) {
                                try {
                                    for (int i = 0; i < len; i++) {
                                        String key = keys.getString(i);

                                        T item = get(key);

                                        if (item != null) {
                                            try {
                                                if (filter == null || filter.filter(item)) {
                                                    cursor.push(item);
                                                }
                                            } catch (Throwable t) {
                                                throw new JiteratorLoadException(t);
                                            }
                                        }
                                    }
                                } catch (JSONException e) {
                                    throw new JiteratorLoadException(e);
                                } catch (PersistenceException e) {
                                    throw new JiteratorLoadException(e);
                                }
                            }
                        };

                        populator.populate();
                        if (filter == null) {
                            populator.setSize(len);
                        }
                        return populator.getCursor();
                    } else {
                        PopulatorThread<T> populator;

                        populator = new PopulatorThread<T>(new JiteratorPopulator<T>() {
                            public void populate(@Nonnull Jiterator<T> iterator) throws Exception {
                                for (int i = 0; i < len; i++) {
                                    String key = keys.getString(i);

                                    T item = get(key);

                                    if (item != null) {
                                        try {
                                            if (filter == null || filter.filter(item)) {
                                                iterator.push(item);
                                            }
                                        } catch (Throwable t) {
                                            throw new RuntimeException(t);
                                        }
                                    }
                                }
                            }
                        });
                        populator.populate();
                        if (filter == null) {
                            populator.setSize(len);
                        }
                        return populator.getResult();
                    }
                }
                return Collections.emptyList();
            } catch (IOException e) {
                throw new PersistenceException(e);
            } catch (JSONException e) {
                throw new PersistenceException(e);
            }
        } finally {
            endCall("list");
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("EXIT: " + RiakCache.class.getName() + ".list()");
        }
    }
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static List<String> parseAttributes(final JSONArray nameList, final JSONArray acodeList) {

    final List<String> result = new ArrayList<String>();

    for (int i = 0; i < nameList.length(); i++) {
        try {//from   w  ww  .  ja  va 2s.  c om
            final String name = nameList.getString(i);
            final int acode = acodeList != null ? Integer.parseInt(acodeList.getString(i).substring(1))
                    : CacheAttribute.NO_ID;
            final CacheAttribute attr = CacheAttribute.getByOcACode(acode);

            if (attr != null) {
                result.add(attr.rawName);
            } else {
                result.add(name);
            }
        } catch (final JSONException e) {
            Log.e("OkapiClient.parseAttributes", e);
        }
    }

    return result;
}

From source file:com.fatsecret.platform.utils.RecipeUtility.java

/**
 * Returns detailed information about the recipe
 * // w w  w .  j a  v a 2 s. c o  m
 * @param json         json object representing of the recipe
 * @return            detailed information about the recipe
 */
public static Recipe parseRecipeFromJSONObject(JSONObject json) {
    String name = json.getString("recipe_name");
    String url = json.getString("recipe_url");
    String description = json.getString("recipe_description");
    Long id = Long.parseLong(json.getString("recipe_id"));

    List<String> images = new ArrayList<String>();
    JSONObject recipeImages = json.getJSONObject("recipe_images");
    JSONArray recipeImage = null;
    try {
        recipeImage = recipeImages.getJSONArray("recipe_image");
    } catch (Exception e) {
        recipeImage = null;
    }

    if (recipeImage != null) {
        for (int i = 0; i < recipeImage.length(); i++) {
            String image = recipeImage.getString(i);
            images.add(image);
        }
    } else {
        String image = recipeImages.getString("recipe_image");
        images.add(image);
    }

    Integer rating = Integer.parseInt(json.getString("rating"));

    List<String> types = new ArrayList<String>();
    JSONObject recipeTypes = json.getJSONObject("recipe_types");

    JSONArray recipeType = null;
    try {
        recipeType = recipeTypes.getJSONArray("recipe_type");
    } catch (Exception e) {
        recipeType = null;
    }

    if (recipeType != null) {
        for (int i = 0; i < recipeType.length(); i++) {
            String type = recipeType.getString(i);
            types.add(type);
        }
    } else {
        String type = recipeTypes.getString("recipe_type");
        types.add(type);
    }

    BigDecimal numberOfServings = new BigDecimal(json.getString("number_of_servings"));

    Integer preparationTime = 0;
    try {
        preparationTime = Integer.parseInt(json.getString("preparation_time_min"));
    } catch (Exception ignore) {
        preparationTime = 0;
    }

    Integer cookingTime = 0;

    try {
        cookingTime = Integer.parseInt(json.getString("cooking_time_min"));
    } catch (Exception ignore) {
        cookingTime = 0;
    }

    List<Category> categories = new ArrayList<Category>();
    JSONObject recipeCategories = json.getJSONObject("recipe_categories");
    JSONArray recipeCategory = null;

    try {
        recipeCategory = recipeCategories.getJSONArray("recipe_category");
    } catch (Exception e) {
        recipeCategory = null;
    }

    if (recipeCategory != null) {
        for (int i = 0; i < recipeCategory.length(); i++) {
            JSONObject recipeCategoryObj = recipeCategory.getJSONObject(i);
            Category category = parseJsonToCategory(recipeCategoryObj);
            categories.add(category);
        }
    } else {
        JSONObject recipeCategoryObj = recipeCategories.getJSONObject("recipe_category");
        Category category = parseJsonToCategory(recipeCategoryObj);
        categories.add(category);
    }

    JSONObject servingSizes = json.getJSONObject("serving_sizes");
    JSONObject servingObj = servingSizes.getJSONObject("serving");
    Serving serving = ServingUtility.parseServingFromJSONObject(servingObj);

    JSONObject directionsObj = json.getJSONObject("directions");
    List<Direction> directions = new ArrayList<Direction>();
    JSONArray directionArray = null;
    try {
        directionArray = directionsObj.getJSONArray("direction");
    } catch (Exception e) {
        directionArray = null;
    }

    if (directionArray != null) {
        for (int i = 0; i < directionArray.length(); i++) {
            JSONObject directionObj = directionArray.getJSONObject(i);
            Direction direction = parseJsonToDirection(directionObj);
            directions.add(direction);
        }
    } else {
        JSONObject directionObj = directionsObj.getJSONObject("direction");
        Direction direction = parseJsonToDirection(directionObj);
        directions.add(direction);
    }

    List<Ingredient> ingredients = new ArrayList<Ingredient>();
    JSONObject ingredientsObj = json.getJSONObject("ingredients");
    JSONArray ingredientArray = null;
    try {
        ingredientArray = ingredientsObj.getJSONArray("ingredient");
    } catch (Exception e) {
        ingredientArray = null;
    }

    if (ingredientArray != null) {
        for (int i = 0; i < ingredientArray.length(); i++) {
            JSONObject ingredientObj = ingredientArray.getJSONObject(i);
            Ingredient ingredient = parseJsonToIngredient(ingredientObj);
            ingredients.add(ingredient);
        }
    } else {
        JSONObject ingredientObj = ingredientsObj.getJSONObject("ingredient");
        Ingredient ingredient = parseJsonToIngredient(ingredientObj);
        ingredients.add(ingredient);
    }

    Recipe recipe = new Recipe();

    recipe.setName(name);
    recipe.setUrl(url);
    recipe.setDescription(description);
    recipe.setId(id);
    recipe.setImages(images);
    recipe.setRating(rating);
    recipe.setTypes(types);
    recipe.setNumberOfServings(numberOfServings);
    recipe.setPreparationTime(preparationTime);
    recipe.setCookingTime(cookingTime);
    recipe.setCategories(categories);
    recipe.setServing(serving);
    recipe.setDirections(directions);
    recipe.setIngredients(ingredients);

    return recipe;
}

From source file:com.norman0406.slimgress.API.Interface.GameBasket.java

private void processDeletedEntityGuids(JSONArray deletedEntityGuids) throws JSONException {
    if (deletedEntityGuids != null) {
        for (int i = 0; i < deletedEntityGuids.length(); i++) {
            mDeletedEntityGuids.add(deletedEntityGuids.getString(i));
        }/* w  w  w .  ja  v a 2  s.  c om*/
    }
}

From source file:com.norman0406.slimgress.API.Interface.GameBasket.java

private void processEnergyGlobGuids(JSONArray energyGlobGuids, String timestamp) throws JSONException {
    if (energyGlobGuids != null && timestamp.length() > 0) {
        for (int i = 0; i < energyGlobGuids.length(); i++) {
            String guid = energyGlobGuids.getString(i);

            XMParticle newParticle = new XMParticle(guid, timestamp);
            mEnergyGlobGuids.add(newParticle);
        }//from ww w  .  j a v  a  2  s  .c om
    }
}

From source file:com.ipo.wiimote.SpeechRecognizer.java

/**
 * Fire an intent to start the speech recognition activity.
 *
 * @param args Argument array with the following string args: [req code][number of matches][prompt string]
 *//*from w ww . java 2  s  .  c o m*/
private void startSpeechRecognitionActivity(JSONArray args) {
    int reqCode = 42; //Hitchhiker?
    int maxMatches = 0;
    String prompt = "";

    try {
        if (args.length() > 0) {
            // Request code - passed back to the caller on a successful operation
            String temp = args.getString(0);
            reqCode = Integer.parseInt(temp);
        }
        if (args.length() > 1) {
            // Maximum number of matches, 0 means the recognizer decides
            String temp = args.getString(1);
            maxMatches = Integer.parseInt(temp);
        }
        if (args.length() > 2) {
            // Optional text prompt
            prompt = args.getString(2);
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, String.format("startSpeechRecognitionActivity exception: %s", e.toString()));
    }

    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
    if (maxMatches > 0)
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxMatches);
    if (!prompt.equals(""))
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
    cordova.startActivityForResult(this, intent, reqCode);
}

From source file:org.uiautomation.ios.IOSCapabilities.java

private List<String> getList(String key) {
    Object o = getCapability(key);
    if (o instanceof List<?>) {
        return (List<String>) o;
    } else if (o instanceof JSONArray) {
        JSONArray a = (JSONArray) o;
        List<String> res = new ArrayList<String>();

        for (int i = 0; i < a.length(); i++) {
            try {
                res.add(a.getString(i));
            } catch (JSONException e) {
                throw new WebDriverException(e);
            }/*from w  w w  .j  av a2  s  .c o  m*/
        }
        return res;
    }
    throw new ClassCastException("expected collection of string, got " + o.getClass());
}