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:org.entrystore.ldcache.util.JsonUtil.java

public static Set<String> jsonArrayToStringSet(JSONArray array) {
    Set<String> result = new HashSet();
    for (int i = 0; i < array.length(); i++) {
        String uri = null;//from w ww  .j  a  v  a  2 s .  co  m
        try {
            uri = array.getString(i);
        } catch (JSONException e) {
            log.warn(e.getMessage());
            continue;
        }
        if (uri != null) {
            result.add(NS.expandNS(uri));
        }
    }
    return result;
}

From source file:com.github.secondsun.catfactsdemo.networking.AsyncTaskbasedFactLoader.java

private AsyncTask<Void, Void, List<String>> makeTask() {
    return new AsyncTask<Void, Void, List<String>>() {
        @Override//  w w  w  .java  2 s .c o  m
        protected List<String> doInBackground(Void... params) {
            try {

                if (data != null && data.size() > 0) {
                    return data;
                }

                Thread.sleep(Constants.DELAY);

                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder().url(Constants.CAT_FACTS_URL).build();

                Response response = client.newCall(request).execute();

                JSONObject responseJson = new JSONObject(response.body().string());
                JSONArray facts = responseJson.getJSONArray("facts");

                ArrayList<String> toReturn = new ArrayList<>(facts.length());

                for (int i = 0; i < facts.length(); i++) {
                    toReturn.add(facts.getString(i));
                }

                data = toReturn;

                return toReturn;

            } catch (InterruptedException | IOException | JSONException e) {
                ArrayList<String> toReturn = new ArrayList<>();
                toReturn.add("Error:" + e.getMessage());
                data = toReturn;
                return toReturn;
            }
        }

        @Override
        protected void onPostExecute(List<String> strings) {
            super.onPostExecute(strings);
            if (activity != null) {
                activity.displayFacts(strings);
            }
        }
    };

}

From source file:uk.ac.imperial.presage2.web.export.DataExportServlet.java

/**
 * Processes the JSON query and returns a table in the form of a double
 * {@link Iterable}.//ww w .  j a v a2s  .c om
 * 
 * @param query
 *            JSON table specification.
 * @return An {@link Iterable} which iterates over each row in the result
 *         set, which is also given as an {@link Iterable}.
 * @throws JSONException
 *             If there is an error in the specification.
 */
Iterable<Iterable<String>> processRequest(JSONObject query) throws JSONException {

    // build source set
    Set<PersistentSimulation> sourceSims = new HashSet<PersistentSimulation>();

    Set<Long> sources = new HashSet<Long>();
    JSONArray sourcesJSON = query.getJSONArray("sources");
    for (int i = 0; i < sourcesJSON.length(); i++) {
        long simId = sourcesJSON.getLong(i);
        PersistentSimulation sim = sto.getSimulationById(simId);
        if (sim != null) {
            // add simulation and all of it's decendents.
            getDecendents(simId, sources);
        }
    }
    // build sourceSims set from simIds we have collected.
    for (Long sim : sources) {
        sourceSims.add(sto.getSimulationById(sim));
    }

    // check type
    JSONArray parametersJSON = query.getJSONArray("parameters");
    boolean timeSeries = false;
    List<IndependentVariable> vars = new ArrayList<IndependentVariable>(parametersJSON.length());
    for (int i = 0; i < parametersJSON.length(); i++) {
        if (parametersJSON.getString(i).equalsIgnoreCase("time"))
            timeSeries = true;
        else
            vars.add(new ParameterColumn(sourceSims, parametersJSON.getString(i)));
    }

    JSONArray columns = query.getJSONArray("columns");
    ColumnDefinition[] columnDefs = new ColumnDefinition[columns.length()];
    for (int i = 0; i < columns.length(); i++) {
        columnDefs[i] = ColumnDefinition.createColumn(columns.getJSONObject(i), timeSeries);
        columnDefs[i].setSources(sourceSims);
    }

    TimeColumn time = timeSeries ? new TimeColumn(sourceSims) : null;
    return new IterableTable(vars.toArray(new IndependentVariable[] {}), time, sourceSims, columnDefs);

}

From source file:com.dimasdanz.kendalipintu.usermodel.UserLoadData.java

@Override
protected List<UserModel> doInBackground(String... args) {
    List<UserModel> userList = new ArrayList<UserModel>();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    JSONObject json = jsonParser.makeHttpRequest(ServerUtilities.getUserListUrl(activity) + current_page, "GET",
            params);/*from   w w  w. j  a  v a 2 s .co m*/
    if (json != null) {
        try {
            if (json.getInt("response") == 1) {
                JSONArray userid = json.getJSONArray("userid");
                JSONArray username = json.getJSONArray("username");
                JSONArray userpass = json.getJSONArray("userpass");
                for (int i = 0; i < userid.length(); i++) {
                    userList.add(new UserModel(userid.get(i).toString(), username.get(i).toString(),
                            userpass.getString(i).toString()));
                }
                return userList;
            } else {
                return null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    } else {
        con = false;
        return null;
    }
}

From source file:com.vladstirbu.cordova.CDVInstagramPlugin.java

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

    this.cbContext = callbackContext;

    if (action.equals("share")) {
        String imageString = args.getString(0);
        this.share(imageString);
        return true;
    } else if (action.equals("isInstalled")) {
        this.isInstalled();
    } else {//from  w w  w  . j a  va  2 s .c  om
        callbackContext.error("Invalid Action");
    }
    return false;
}

From source file:com.github.sgelb.booket.SearchResultActivity.java

private void processResult(String result) {
    JSONArray items = null;/*w  ww  . j av a2s  . c o  m*/
    try {
        JSONObject jsonObject = new JSONObject(result);
        items = jsonObject.getJSONArray("items");
    } catch (JSONException e) {
        noResults.setVisibility(View.VISIBLE);
        return;
    }

    try {

        // iterate over items aka books
        Log.d("R2R", "Items: " + items.length());
        for (int i = 0; i < items.length(); i++) {
            Log.d("R2R", "\nBook " + (i + 1));
            JSONObject item = (JSONObject) items.get(i);
            JSONObject info = item.getJSONObject("volumeInfo");
            Book book = new Book();

            // add authors
            String authors = "";
            if (info.has("authors")) {
                JSONArray jAuthors = info.getJSONArray("authors");
                for (int j = 0; j < jAuthors.length() - 1; j++) {
                    authors += jAuthors.getString(j) + ", ";
                }
                authors += jAuthors.getString(jAuthors.length() - 1);
            } else {
                authors = "n/a";
            }
            book.setAuthors(authors);
            Log.d("R2R", "authors " + book.getAuthors());

            // add title
            if (info.has("title")) {
                book.setTitle(info.getString("title"));
                Log.d("R2R", "title " + book.getTitle());
            }

            // add pageCount
            if (info.has("pageCount")) {
                book.setPageCount(info.getInt("pageCount"));
                Log.d("R2R", "pageCount " + book.getPageCount());
            }

            // add publisher
            if (info.has("publisher")) {
                book.setPublisher(info.getString("publisher"));
                Log.d("R2R", "publisher " + book.getPublisher());
            }

            // add description
            if (info.has("description")) {
                book.setDescription(info.getString("description"));
                Log.d("R2R", "description " + book.getDescription());
            }

            // add isbn
            if (info.has("industryIdentifiers")) {
                JSONArray ids = info.getJSONArray("industryIdentifiers");
                for (int k = 0; k < ids.length(); k++) {
                    JSONObject id = ids.getJSONObject(k);
                    if (id.getString("type").equalsIgnoreCase("ISBN_13")) {
                        book.setIsbn(id.getString("identifier"));
                        break;
                    }
                    if (id.getString("type").equalsIgnoreCase("ISBN_10")) {
                        book.setIsbn(id.getString("identifier"));
                    }
                }
                Log.d("R2R", "isbn " + book.getIsbn());
            }

            // add published date
            if (info.has("publishedDate")) {
                book.setYear(info.getString("publishedDate").substring(0, 4));
                Log.d("R2R", "publishedDate " + book.getYear());
            }

            // add cover thumbnail
            book.setThumbnailBitmap(defaultThumbnail);

            if (info.has("imageLinks")) {
                // get cover url from google
                JSONObject imageLinks = info.getJSONObject("imageLinks");
                if (imageLinks.has("thumbnail")) {
                    book.setThumbnailUrl(imageLinks.getString("thumbnail"));
                }
            } else if (book.getIsbn() != null) {
                // get cover url from amazon
                String amazonCoverUrl = "http://ecx.images-amazon.com/images/P/" + isbn13to10(book.getIsbn())
                        + ".01._SCMZZZZZZZ_.jpg";
                book.setThumbnailUrl(amazonCoverUrl);
            }

            // download cover thumbnail
            if (book.getThumbnailUrl() != null && !book.getThumbnailUrl().isEmpty()) {
                new DownloadThumbNail(book).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                        book.getThumbnailUrl());
                Log.d("R2R", "thumbnail " + book.getThumbnailUrl());
            }

            // add google book id
            if (item.has("id")) {
                book.setGoogleId(item.getString("id"));
            }

            bookList.add(book);

        }
    } catch (Exception e) {
        Log.d("R2R", "Exception: " + e.toString());
        // FIXME: catch exception
    }
}

From source file:com.google.android.gcm.demo.app.GCMIntentService.java

@Override
protected void onMessage(Context context, Intent intent) {
    String api = intent.getStringExtra("api");
    Log.i(TAG, "Received message: " + api);

    // get list of all mp3 files now
    AndroidHttpClient client = null;/*from   w ww .j  a  v a  2s . c  o  m*/
    try {
        client = AndroidHttpClient.newInstance("Android");

        HttpGet httpGet = new HttpGet(api);
        HttpResponse response;
        try {
            response = client.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());
            JSONArray array = new JSONArray(json);
            ArrayList<String> urls = new ArrayList<String>();
            for (int i = 0; i < array.length(); ++i) {
                String mp3Link = array.getString(i);
                urls.add(mp3Link);
            }

            // start DownloadService
            Intent itent = new Intent(this, DownloadService.class);
            itent.putExtra(CommonUtilities.EXTRA_URLS, urls);
            startService(itent);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent == null) {
        return;//ww  w  .  j a  va 2 s.  c o  m
    }
    final boolean force = intent.getBooleanExtra("force", false);
    try {
        Locale loc = Locale.getDefault();
        String lang = loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php; T-values if present both T and B
        if (lang == null || lang.length() == 0) {
            lang = "";
        }

        int serverVersion = intent.getIntExtra("serverVersion", -1);
        boolean fromPush = serverVersion != -1;
        JSONObject versionJson = null;
        if (!fromPush) {
            versionJson = getVersion(true);
            serverVersion = versionJson.getInt("version");
        }
        int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1);
        final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, "");

        if (serverVersion <= localVersion && !force && lang.equals(localLanguage)
                && !LOCAL_DEFINITION_TESTING) {
            // don't update
            DebugLog.i("Nothing new, not updating");
            return;
        }

        // update but don't notify about it.
        boolean firstLaunchNoUpdate = ((localVersion == -1
                && getVersion(false).getInt("version") == serverVersion) || !lang.equals(localLanguage));

        if (!firstLaunchNoUpdate) {
            DebugLog.i("There are new definitions available!");
        }

        handleAuthorMessage(versionJson, lang, intent, fromPush);

        InputStream is = getIS(URL_TICKETS_ID);
        try {
            String json = readResult(is);

            JSONObject o = new JSONObject(json);
            JSONArray array = o.getJSONArray("tickets");

            final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase();
            for (int i = 0; i < array.length(); i++) {
                final JSONObject city = array.getJSONObject(i);
                try {

                    final ContentValues cv = new ContentValues();
                    cv.put(Cities._ID, city.getInt("id"));
                    cv.put(Cities.CITY, getStringLocValue(city, lang, "city"));
                    if (city.has("city_pubtran")) {
                        cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran"));
                    }
                    cv.put(Cities.COUNTRY, city.getString("country"));
                    cv.put(Cities.CURRENCY, city.getString("currency"));
                    cv.put(Cities.DATE_FORMAT, city.getString("dateFormat"));
                    cv.put(Cities.IDENTIFICATION, city.getString("identification"));
                    cv.put(Cities.LAT, city.getDouble("lat"));
                    cv.put(Cities.LON, city.getDouble("lon"));
                    cv.put(Cities.NOTE, getStringLocValue(city, lang, "note"));
                    cv.put(Cities.NUMBER, city.getString("number"));
                    cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom"));
                    cv.put(Cities.P_DATE_TO, city.getString("pDateTo"));
                    cv.put(Cities.P_HASH, city.getString("pHash"));
                    cv.put(Cities.PRICE, city.getString("price"));
                    cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote"));
                    cv.put(Cities.REQUEST, city.getString("request"));
                    cv.put(Cities.VALIDITY, city.getInt("validity"));
                    if (city.has("confirmReq")) {
                        cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq"));
                    }
                    if (city.has("confirm")) {
                        cv.put(Cities.CONFIRM, city.getString("confirm"));
                    }

                    final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers");
                    for (int j = 0; j < additionalNumbers.length() && j < 3; j++) {
                        cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j));
                    }

                    db.beginTransaction();
                    int count = db.update(DatabaseHelper.CITY_TABLE_NAME, cv,
                            Cities._ID + " = " + cv.getAsInteger(Cities._ID), null);
                    if (count == 0) {
                        db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv);
                    }

                    db.setTransactionSuccessful();
                    getContentResolver().notifyChange(Cities.CONTENT_URI, null);
                } finally {
                    if (db.inTransaction()) {
                        db.endTransaction();
                    }
                }
            }
            Preferences.set(c, Preferences.DATA_VERSION, serverVersion);
            Preferences.set(c, Preferences.DATA_LANGUAGE, lang);
            if (!firstLaunchNoUpdate && !fromPush) {
                final int finalServerVersion = serverVersion;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UpdateService.this,
                                getString(R.string.cities_update_completed, finalServerVersion),
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
            if (LOCAL_DEFINITION_TESTING) {
                DebugLog.w(
                        "Local definition testing - data updated from assets - must be removed in production!");
            }
        } finally {
            is.close();
        }
    } catch (IOException e) {
        DebugLog.e("IOException when calling update: " + e.getMessage(), e);
    } catch (JSONException e) {
        DebugLog.e("JSONException when calling update: " + e.getMessage(), e);
    }
}

From source file:cc.vileda.sipgatesync.contacts.SipgateContactSyncAdapter.java

private List<String> jsonArrayToList(final JSONArray arr) throws JSONException {
    final List<String> list = new ArrayList<>();
    for (int i = 0; i < arr.length(); i++) {
        list.add(arr.getString(i));
    }/*  ww  w  .j  av a 2  s.  c om*/

    return list;
}

From source file:com.frostytornado.cordova.plugin.ad.admob.Plugin.java

private void setUp(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    //Activity activity=cordova.getActivity();
    //webView//from  w  w  w  .  j a v  a2s. co  m
    //args.length()
    //args.getString(0)
    //args.getString(1)
    //args.getInt(0)
    //args.getInt(1)
    //args.getBoolean(0)
    //args.getBoolean(1)
    //JSONObject json = args.optJSONObject(0);
    //json.optString("bannerAdUnit")
    //json.optString("interstitialAdUnit")
    //JSONObject inJson = json.optJSONObject("inJson");
    //final String bannerAdUnit = args.getString(0);
    //final String interstitialAdUnit = args.getString(1);            
    //final boolean isOverlap = args.getBoolean(2);            
    //final boolean isTest = args.getBoolean(3);
    //final String[] zoneIds = new String[args.getJSONArray(4).length()];
    //for (int i = 0; i < args.getJSONArray(4).length(); i++) {
    //   zoneIds[i] = args.getJSONArray(4).getString(i);
    //}         
    //Log.d(LOG_TAG, String.format("%s", bannerAdUnit));         
    //Log.d(LOG_TAG, String.format("%s", interstitialAdUnit));
    //Log.d(LOG_TAG, String.format("%b", isOverlap));
    //Log.d(LOG_TAG, String.format("%b", isTest));      
    final String bannerAdUnit = args.getString(0);
    final String interstitialAdUnit = args.getString(1);
    final boolean isOverlap = args.getBoolean(2);
    final boolean isTest = args.getBoolean(3);
    Log.d(LOG_TAG, String.format("%s", bannerAdUnit));
    Log.d(LOG_TAG, String.format("%s", interstitialAdUnit));
    Log.d(LOG_TAG, String.format("%b", isOverlap));
    Log.d(LOG_TAG, String.format("%b", isTest));

    callbackContextKeepCallback = callbackContext;

    if (isOverlap) {
        pluginDelegate = new AdmobOverlap(this);
    } else {
        pluginDelegate = new AdmobSplit(this);
    }

    cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            _setUp(bannerAdUnit, interstitialAdUnit, isOverlap, isTest);
        }
    });
}