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.jennifer.ui.util.JSONUtil.java

public static void reverse(JSONArray domain) {
    JSONArray temp = new JSONArray();
    for (int i = 0, len = domain.length(); i < len; i++) {
        temp.put(i, domain.get(i));
    }/*ww w  .  j ava  2  s. c om*/

    for (int i = temp.length() - 1, j = 0; i >= 0; i--, j++) {
        domain.put(j, temp.get(i));
    }
}

From source file:com.dimasdanz.kendalipintu.logmodel.LogLoadData.java

@Override
protected ArrayList<String> doInBackground(Void... args) {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    JSONObject json = jsonParser.makeHttpRequest(ServerUtilities.getLogDateUrl(activity), "GET", params);
    if (json != null) {
        try {// ww  w.  j av  a 2s.  c  o m
            JSONArray date = json.getJSONArray("date");
            for (int i = 0; i < date.length(); i++) {
                listDataHeader.add(date.get(i).toString());
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        return listDataHeader;
    } else {
        Log.d("Log", "Failed");
        return null;
    }
}

From source file:com.colossaldb.dnd.prefs.AppPreferences.java

private static void writeToPrefList(SharedPreferences preferences, String listKey, String title, String detail)
        throws JSONException {
    //JSONArray events = LOCAL_STORE ;//getJSONArray(preferences, listKey);
    JSONArray events = getJSONArray(preferences, listKey);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(TIMESTAMP_KEY, DF.format(new Date(System.currentTimeMillis())));
    jsonObject.put(TITLE_KEY, title);/*  ww  w .  j  av  a  2 s. c  o  m*/
    jsonObject.put(DETAIL_KEY, detail);
    events.put(jsonObject);

    if (events.length() > MAX_LIST_SIZE) {
        JSONArray newArray = new JSONArray();
        for (int i = events.length() - MAX_LIST_SIZE; i < MAX_LIST_SIZE; i++) {
            newArray.put(events.get(i));
        }
        events = newArray;
    }

    //LOCAL_STORE = events;
    preferences.edit().putString(listKey, events.toString()).apply();
}

From source file:com.laquysoft.droidconnl.TriviaQuestion.java

public TriviaQuestion(JSONObject jsonobj) {
    try {/* w  w w .j  a va  2s . c  o m*/
        question = jsonobj.getString("question");
        if (jsonobj.has("bitmap")) {
            bitmapID = jsonobj.getString("bitmap");
        }

        answers = new ArrayList<String>();

        JSONArray questionList = jsonobj.getJSONArray("answers");
        for (int i = 0; i < questionList.length(); i++) {
            String answerString = (String) questionList.get(i);
            answers.add(answerString);
        }

        correctAnswer = jsonobj.getInt("correctAnswer");
        rightMessage = jsonobj.getString("rightMessage");
        wrongMessage = jsonobj.getString("wrongMessage");
    } catch (JSONException e) {
        Log.e("AndroidHunt", "Error parsing TriviaQuestion " + e.getStackTrace().toString());
    }
}

From source file:net.fred.feedex.activity.EditFeedActivity.java

/**
 * This is where the bulk of our work is done. This function is called in a background thread and should generate a new set of data to be
 * published by the loader.//from  w  w  w. j  a va  2s. co  m
 */
@Override
public ArrayList<HashMap<String, String>> loadInBackground() {
    try {
        HttpURLConnection conn = NetworkUtils
                .setupConnection("https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=" + mSearchText);
        try {
            String jsonStr = new String(NetworkUtils.getBytes(conn.getInputStream()));

            // Parse results
            final ArrayList<HashMap<String, String>> results = new ArrayList<>();
            JSONObject response = new JSONObject(jsonStr).getJSONObject("responseData");
            JSONArray entries = response.getJSONArray("entries");
            for (int i = 0; i < entries.length(); i++) {
                try {
                    JSONObject entry = (JSONObject) entries.get(i);
                    String url = entry.get(EditFeedActivity.FEED_SEARCH_URL).toString();
                    if (!url.isEmpty()) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put(EditFeedActivity.FEED_SEARCH_TITLE, Html
                                .fromHtml(entry.get(EditFeedActivity.FEED_SEARCH_TITLE).toString()).toString());
                        map.put(EditFeedActivity.FEED_SEARCH_URL, url);
                        map.put(EditFeedActivity.FEED_SEARCH_DESC, Html
                                .fromHtml(entry.get(EditFeedActivity.FEED_SEARCH_DESC).toString()).toString());

                        results.add(map);
                    }
                } catch (Exception ignored) {
                }
            }

            return results;
        } finally {
            conn.disconnect();
        }
    } catch (Exception e) {
        Dog.e("Error", e);
        return null;
    }
}

From source file:org.wso2.iot.agent.utils.CommonUtils.java

public static AppRestriction getAppRestrictionTypeAndList(Operation operation, ResultPayload resultBuilder,
        Resources resources) throws AndroidAgentException {
    AppRestriction appRestriction = new AppRestriction();
    JSONArray permittedApps = null;
    try {//from   w w w. j  a v  a2s  .c o m
        JSONObject payload = new JSONObject(operation.getPayLoad().toString());
        appRestriction.setRestrictionType((String) payload.get(Constants.AppRestriction.RESTRICTION_TYPE));
        if (!payload.isNull(Constants.AppRestriction.RESTRICTED_APPLICATIONS)) {
            permittedApps = payload.getJSONArray(Constants.AppRestriction.RESTRICTED_APPLICATIONS);
        }
    } catch (JSONException e) {
        if (resources != null && resultBuilder != null) {
            operation.setStatus(resources.getString(R.string.operation_value_error));
            resultBuilder.build(operation);
        }
        throw new AndroidAgentException("Invalid JSON format.", e);
    }

    List<String> restrictedPackages = new ArrayList<>();

    if (permittedApps != null) {
        for (int i = 0; i < permittedApps.length(); i++) {
            try {
                restrictedPackages.add((String) ((JSONObject) permittedApps.get(i))
                        .get(Constants.AppRuntimePermission.PACKAGE_NAME));
            } catch (JSONException e) {
                if (resources != null && resultBuilder != null) {
                    operation.setStatus(resources.getString(R.string.operation_value_error));
                    resultBuilder.build(operation);
                }
                throw new AndroidAgentException("Invalid JSON format", e);
            }
        }
    }

    appRestriction.setRestrictedList(restrictedPackages);
    return appRestriction;
}

From source file:org.wso2.iot.agent.utils.CommonUtils.java

public static AppRestriction getAppRuntimePermissionTypeAndList(Operation operation,
        ResultPayload resultBuilder, Resources resources) throws AndroidAgentException {
    AppRestriction appRestriction = new AppRestriction();
    JSONArray restrictedApps = null;
    try {//from  w w w.j a  v a 2  s .  c om
        JSONObject payload = new JSONObject(operation.getPayLoad().toString());
        appRestriction.setRestrictionType((String) payload.get(Constants.AppRuntimePermission.PERMISSION_TYPE));
        if (!payload.isNull(Constants.AppRuntimePermission.PERMITTED_APPS)) {
            restrictedApps = payload.getJSONArray(Constants.AppRuntimePermission.PERMITTED_APPS);
        }
    } catch (JSONException e) {
        if (resources != null && resultBuilder != null) {
            operation.setStatus(resources.getString(R.string.operation_value_error));
            resultBuilder.build(operation);
        }
        throw new AndroidAgentException("Invalid JSON format.", e);
    }

    List<String> restrictedPackages = new ArrayList<>();

    if (restrictedApps != null) {
        for (int i = 0; i < restrictedApps.length(); i++) {
            try {
                restrictedPackages.add((String) ((JSONObject) restrictedApps.get(i))
                        .get(Constants.AppRestriction.PACKAGE_NAME));
            } catch (JSONException e) {
                if (resources != null && resultBuilder != null) {
                    operation.setStatus(resources.getString(R.string.operation_value_error));
                    resultBuilder.build(operation);
                }
                throw new AndroidAgentException("Invalid JSON format", e);
            }
        }
    }

    appRestriction.setRestrictedList(restrictedPackages);
    return appRestriction;
}

From source file:com.cch.aj.entryrecorder.frame.MainJFrame.java

private void FillMaterialTable(String data) {
    try {/*  w w w . ja v a2  s .  c o m*/
        JSONObject json = new JSONObject(data);
        JSONArray items = (JSONArray) json.get("items");
        for (int i = 0; i < items.length(); i++) {
            JSONObject record = (JSONObject) items.get(i);
            DefaultTableModel model = (DefaultTableModel) this.tblMaterial.getModel();
            String time = record.getString("time");
            String polymer = record.getString("polymer");
            String additive1 = record.getString("additive1");
            String additive2 = record.getString("additive2");
            String additive3 = record.getString("additive3");
            String polymer_batch1 = record.getString("polymer_batch1");
            String polymer_batch2 = record.getString("polymer_batch2");
            String additive1_batch1 = record.getString("additive1_batch1");
            String additive1_batch2 = record.getString("additive1_batch2");
            String additive2_batch1 = record.getString("additive2_batch1");
            String additive2_batch2 = record.getString("additive2_batch2");
            String additive3_batch1 = record.getString("additive3_batch1");
            String additive3_batch2 = record.getString("additive3_batch2");
            if (!polymer.equals("")) {
                model.addRow(new Object[] { time, "polymer", polymer });
            }
            if (!polymer_batch1.equals("")) {
                model.addRow(new Object[] { time, "polymer_batch1", polymer_batch1 });
            }
            if (!polymer_batch2.equals("")) {
                model.addRow(new Object[] { time, "polymer_batch2", polymer_batch2 });
            }
            if (!additive1.equals("")) {
                model.addRow(new Object[] { time, "additive1", additive1 });
            }
            if (!additive1_batch1.equals("")) {
                model.addRow(new Object[] { time, "additive1_batch1", additive1_batch1 });
            }
            if (!additive1_batch2.equals("")) {
                model.addRow(new Object[] { time, "additive1_batch2", additive1_batch2 });
            }
            if (!additive2.equals("")) {
                model.addRow(new Object[] { time, "additive2", additive2 });
            }
            if (!additive2_batch1.equals("")) {
                model.addRow(new Object[] { time, "additive2_batch1", additive2_batch1 });
            }
            if (!additive2_batch2.equals("")) {
                model.addRow(new Object[] { time, "additive2_batch2", additive2_batch2 });
            }
            if (!additive3.equals("")) {
                model.addRow(new Object[] { time, "additive3", additive3 });
            }
            if (!additive3_batch1.equals("")) {
                model.addRow(new Object[] { time, "additive3_batch1", additive3_batch1 });
            }
            if (!additive3_batch2.equals("")) {
                model.addRow(new Object[] { time, "additive3_batch2", additive3_batch2 });
            }
        }
    } catch (JSONException ex) {
        Logger.getLogger(MainJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.oakesville.mythling.util.MythTvParser.java

/**
 * @param mediaType//from   w  w  w.j  a  va 2  s.  c o m
 * @param storageGroup media storage group
 * @param basePath     base path to trim from filename (when no storage group)
 */
public MediaList parseMediaList(MediaType mediaType, Map<String, StorageGroup> storageGroups, String basePath)
        throws JSONException, ParseException {
    MediaList mediaList = new MediaList();
    mediaList.setMediaType(mediaType);
    mediaList.setBasePath(basePath);
    long startTime = System.currentTimeMillis();
    JSONObject list = new JSONObject(json);
    SortType sortType = appSettings.getMediaSettings().getSortType();
    if (list.has("VideoMetadataInfoList")) {
        // videos, movies, or tvSeries
        MediaSettings mediaSettings = appSettings.getMediaSettings();
        JSONObject infoList = list.getJSONObject("VideoMetadataInfoList");
        if (infoList.has("Version"))
            mediaList.setMythTvVersion(infoList.getString("Version"));
        mediaList.setRetrieveDate(parseMythDateTime(infoList.getString("AsOf")));
        JSONArray vids = infoList.getJSONArray("VideoMetadataInfos");

        String[] movieDirs = appSettings.getMovieDirs();
        String[] tvSeriesDirs = appSettings.getTvSeriesDirs();
        String[] vidExcludeDirs = appSettings.getVidExcludeDirs();

        int count = 0;
        for (int i = 0; i < vids.length(); i++) {
            JSONObject vid = (JSONObject) vids.get(i);
            MediaType type = MediaType.videos;
            // determine type
            if (mediaSettings.getTypeDeterminer() == MediaTypeDeterminer.directories) {
                if (vid.has("FileName")) {
                    String filePath = vid.getString("FileName");
                    if (storageGroups.get(appSettings.getVideoStorageGroup()) == null
                            && filePath.startsWith(basePath + "/"))
                        filePath = filePath.substring(basePath.length() + 1);

                    for (String movieDir : movieDirs) {
                        if (filePath.startsWith(movieDir)) {
                            type = MediaType.movies;
                            break;
                        }
                    }
                    for (String tvDir : tvSeriesDirs) {
                        if (filePath.startsWith(tvDir)) {
                            type = MediaType.tvSeries;
                            break;
                        }
                    }
                    for (String vidExcludeDir : vidExcludeDirs) {
                        if (filePath.startsWith(vidExcludeDir)) {
                            type = null;
                            break;
                        }
                    }
                }
            } else if (mediaSettings.getTypeDeterminer() == MediaTypeDeterminer.metadata) {
                if (vid.has("Season")) {
                    String season = vid.getString("Season");
                    if (!season.isEmpty() && !season.equals("0"))
                        type = MediaType.tvSeries;
                }
                if (type != MediaType.tvSeries && vid.has("Inetref")) {
                    String inetref = vid.getString("Inetref");
                    if (!inetref.isEmpty() && !inetref.equals("00000000"))
                        type = MediaType.movies;
                }
            }

            if (type == mediaType) {
                try {
                    mediaList.addItemUnderPathCategory(buildVideoItem(type, vid, storageGroups));
                    count++;
                } catch (NumberFormatException ex) {
                    Log.e(TAG, "NumberFormatException for " + type + " at index: " + count);
                }
            }
        }
        mediaList.setCount(count);
    } else if (list.has("ProgramList")) {
        // recordings
        JSONObject infoList = list.getJSONObject("ProgramList");
        if (infoList.has("Version"))
            mediaList.setMythTvVersion(infoList.getString("Version"));
        mediaList.setRetrieveDate(parseMythDateTime(infoList.getString("AsOf")));
        mediaList.setCount(infoList.getString("Count"));
        JSONArray recs = infoList.getJSONArray("Programs");
        for (int i = 0; i < recs.length(); i++) {
            JSONObject rec = (JSONObject) recs.get(i);
            try {
                Recording recItem = buildRecordingItem(rec, storageGroups);
                if (!"Deleted".equals(recItem.getRecordingGroup())
                        && !"LiveTV".equals(recItem.getRecordingGroup())) {
                    ViewType viewType = appSettings.getMediaSettings().getViewType();
                    if ((viewType == ViewType.list || viewType == ViewType.split)
                            && (sortType == null || sortType == SortType.byTitle)) {
                        // categorize by title
                        Category cat = mediaList.getCategory(recItem.getTitle());
                        if (cat == null) {
                            cat = new Category(recItem.getTitle(), MediaType.recordings);
                            mediaList.addCategory(cat);
                        }
                        cat.addItem(recItem);
                    } else {
                        mediaList.addItem(recItem);
                    }
                } else {
                    mediaList.setCount(mediaList.getCount() - 1); // otherwise reported count will be off
                }
            } catch (NumberFormatException ex) {
                Log.e(TAG, "NumberFormatException for recording at index: " + i);
            }
        }
    } else if (list.has("ProgramGuide")) {
        // live tv
        JSONObject infoList = list.getJSONObject("ProgramGuide");
        if (infoList.has("Version"))
            mediaList.setMythTvVersion(infoList.getString("Version"));
        mediaList.setRetrieveDate(parseMythDateTime(infoList.getString("AsOf")));
        mediaList.setCount(infoList.getString("Count"));
        JSONArray chans = infoList.getJSONArray("Channels");
        for (int i = 0; i < chans.length(); i++) {
            JSONObject chanInfo = (JSONObject) chans.get(i);
            try {
                Item show = buildLiveTvItem(chanInfo);
                if (show != null) {
                    mediaList.addItem(show);
                    show.setPath("");
                }
            } catch (NumberFormatException ex) {
                Log.e(TAG, "NumberFormatException for live TV at index: " + i);
            }
        }
    } else if (mediaType == MediaType.music) {
        JSONArray strList = list.getJSONArray("StringList");
        mediaList.setCount(strList.length());
        StorageGroup musicStorageGroup = storageGroups.get(appSettings.getMusicStorageGroup());
        Map<String, String> dirToAlbumArt = null;
        if (appSettings.isMusicArtAlbum())
            dirToAlbumArt = new HashMap<String, String>();
        for (int i = 0; i < strList.length(); i++) {
            String filepath = strList.getString(i);
            int lastSlash = filepath.lastIndexOf('/');
            String filename = filepath;
            String path = "";
            if (lastSlash > 0 && filepath.length() > lastSlash + 1) {
                filename = filepath.substring(lastSlash + 1);
                path = filepath.substring(0, lastSlash);
            }
            String title = filename;
            String format = null;
            int lastDot = filename.lastIndexOf('.');
            if (lastDot > 0 && filename.length() > lastDot + 1) {
                title = filename.substring(0, lastDot);
                format = filename.substring(lastDot + 1);
            }

            if ("jpg".equals(format) && "cover".equals(title)) {
                if (dirToAlbumArt != null)
                    dirToAlbumArt.put(path, title + ".jpg");
            } else if ("jpg".equals(format) || "jpeg".equals(format) // TODO: better check for image type
                    || "png".equals(format) || "gif".equals(format)) {
                if (dirToAlbumArt != null) {
                    String imgPath = dirToAlbumArt.get(title + '.' + format);
                    if (!"cover.jpg".equals(imgPath)) // prefer cover.jpg
                        dirToAlbumArt.put(path, title + '.' + format);
                }
            } else {
                Song song = new Song(String.valueOf(i), title);
                song.setPath(path);
                song.setFileBase(path + "/" + title);
                song.setFormat(format);
                song.setStorageGroup(musicStorageGroup);
                mediaList.addItemUnderPathCategory(song);
            }
        }
        if (dirToAlbumArt != null && !dirToAlbumArt.isEmpty()) {
            // set album art
            for (Item item : mediaList.getAllItems()) {
                String art = dirToAlbumArt.get(item.getPath());
                if (art != null)
                    ((Song) item).setAlbumArt(art);
            }
        }
    }
    if (sortType != null) {
        startTime = System.currentTimeMillis();
        mediaList.sort(sortType, true);
        if (BuildConfig.DEBUG)
            Log.d(TAG, " -> media list parse/sort time: " + (System.currentTimeMillis() - startTime) + " ms");
    } else {
        if (BuildConfig.DEBUG)
            Log.d(TAG, " -> media list parse time: " + (System.currentTimeMillis() - startTime) + " ms");
    }
    return mediaList;
}

From source file:com.oakesville.mythling.util.MythTvParser.java

private Video buildVideoItem(MediaType type, JSONObject vid, Map<String, StorageGroup> storageGroups)
        throws JSONException, ParseException {
    Video item;//from  w w w  .ja  va 2 s  .  c  o m
    if (type == MediaType.movies) {
        item = new Movie(vid.getString("Id"), vid.getString("Title"));
    } else if (type == MediaType.tvSeries) {
        item = new TvEpisode(vid.getString("Id"), vid.getString("Title"));
        if (vid.has("Season")) {
            String season = vid.getString("Season");
            if (!season.isEmpty() && !season.equals("0"))
                ((TvEpisode) item).setSeason(Integer.parseInt(season));
        }
        if (vid.has("Episode")) {
            String episode = vid.getString("Episode");
            if (!episode.isEmpty() && !episode.equals("0"))
                ((TvEpisode) item).setEpisode(Integer.parseInt(episode));
        }
    } else {
        item = new Video(vid.getString("Id"), vid.getString("Title"));
    }

    String filename = vid.getString("FileName");
    int lastdot = filename.lastIndexOf('.');
    item.setFileBase(filename.substring(0, lastdot));
    item.setFormat(filename.substring(lastdot + 1));
    if (storageGroups != null)
        item.setStorageGroup(storageGroups.get(appSettings.getVideoStorageGroup()));

    if (vid.has("SubTitle")) {
        String subtitle = vid.getString("SubTitle");
        if (!subtitle.isEmpty())
            item.setSubTitle(subtitle);
    }
    if (vid.has("Director")) {
        String director = vid.getString("Director");
        if (!director.isEmpty() && !director.equals("Unknown"))
            item.setDirector(director);
    }
    if (vid.has("Description")) {
        String description = vid.getString("Description");
        if (!description.equals("None"))
            item.setSummary(description);
    }

    if (vid.has("Inetref")) {
        String inetref = vid.getString("Inetref");
        if (!inetref.isEmpty() && !inetref.equals("00000000"))
            item.setInternetRef(inetref);
    }
    if (vid.has("HomePage")) {
        String pageUrl = vid.getString("HomePage");
        if (!pageUrl.isEmpty())
            item.setPageUrl(pageUrl);
    }
    if (vid.has("ReleaseDate")) {
        String releaseDate = vid.getString("ReleaseDate");
        if (!releaseDate.isEmpty()) {
            String dateStr = releaseDate.replace('T', ' ');
            if (dateStr.endsWith("Z"))
                dateStr = dateStr.substring(0, dateStr.length() - 1);
            Date date = Localizer.SERVICE_DATE_FORMAT.parse(dateStr + " UTC");
            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            cal.setTime(date);
            item.setYear(cal.get(Calendar.YEAR));
        }
    }
    if (vid.has("UserRating")) {
        String rating = vid.getString("UserRating");
        if (!rating.isEmpty() && !rating.equals("0"))
            item.setRating(Float.parseFloat(rating) / 2);
    }
    if (vid.has("Length")) {
        item.setLength(Integer.parseInt(vid.getString("Length")) * 60);
    }
    if (vid.has("Artwork")) {
        String artSgName = appSettings.getArtworkStorageGroup(type);
        StorageGroup artworkStorageGroup = storageGroups == null || AppSettings.ARTWORK_NONE.equals(artSgName)
                ? null
                : storageGroups.get(artSgName);
        if (artworkStorageGroup != null) {
            JSONObject artwork = vid.getJSONObject("Artwork");
            if (artwork.has("ArtworkInfos")) {
                JSONArray artworkInfos = artwork.getJSONArray("ArtworkInfos");
                for (int i = 0; i < artworkInfos.length(); i++) {
                    JSONObject artworkInfo = (JSONObject) artworkInfos.get(i);
                    if (artworkInfo.has("StorageGroup")
                            && artworkStorageGroup.getName().equals(artworkInfo.getString("StorageGroup"))) {
                        if (artworkInfo.has("URL")) {
                            String url = artworkInfo.getString("URL");
                            // assumes FileName is last parameter
                            int amp = url.lastIndexOf("&FileName=");
                            if (amp > 0) {
                                String artPath = url.substring(amp + 10);
                                if (artPath.startsWith("/")) // indicates no video storage group
                                {
                                    for (String artDir : artworkStorageGroup.getDirectories()) {
                                        if (artPath.startsWith(artDir)) {
                                            artPath = artPath.substring(artDir.length() + 1);
                                            break;
                                        }
                                    }
                                }
                                item.setArtwork(artPath);
                            }
                        }
                    }
                }
            }
        }
    }

    if (vid.has("transcoded"))
        item.setTranscoded("true".equalsIgnoreCase(vid.getString("transcoded")));

    return item;
}