Example usage for org.json JSONException toString

List of usage examples for org.json JSONException toString

Introduction

In this page you can find the example usage for org.json JSONException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.cmackay.plugins.googleanalytics.GoogleAnalyticsPlugin.java

private void send(final String rawArgs, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            GoogleAnalyticsPlugin plugin = GoogleAnalyticsPlugin.this;
            if (plugin.hasTracker(callbackContext)) {
                try {
                    JSONArray args = new JSONArray(rawArgs);
                    plugin.tracker.send(objectToMap(args.getJSONObject(0)));
                    callbackContext.success();
                } catch (JSONException e) {
                    callbackContext.error(e.toString());
                }//from ww  w. jav  a 2s  .c o  m
            }
        }
    });
}

From source file:com.krayzk9s.imgurholo.ui.AlbumsFragment.java

public void onGetObject(Object object, String tag) {
    Boolean hasImages = false;/*from   www  . j a va  2 s.com*/
    JSONObject imagesData = (JSONObject) object;
    try {
        JSONArray imageArray = imagesData.getJSONArray("data");
        for (int i = 0; i < imageArray.length(); i++) {
            JSONObject imageData = imageArray.getJSONObject(i);
            Log.d("adding album...", imageData.getString("id"));
            if (!imageData.getString(ImgurHoloActivity.IMAGE_DATA_COVER).equals("[[")) {
                urls.add("http://imgur.com/" + imageData.getString(ImgurHoloActivity.IMAGE_DATA_COVER)
                        + "m.png");
                ids.add(imageData.getString("id"));
            }
        }
        hasImages = imageArray.length() > 0;

    } catch (JSONException e) {
        Log.e("Error!", e.toString());
        imagesData = null;
    }
    if (hasImages)
        imageAdapter.notifyDataSetChanged();
    else if (imagesData != null)
        noImageView.setVisibility(View.VISIBLE);
    else
        errorText.setVisibility(View.VISIBLE);
    if (mPullToRefreshLayout != null)
        mPullToRefreshLayout.setRefreshComplete();
}

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

private void processResult(String result) {
    JSONArray items = null;/*from   www .  j a  va  2s  .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:org.openmrs.mobile.listeners.findPatients.LastViewedPatientListener.java

@Override
public void onResponse(JSONObject response) {
    List<Patient> patientsList = new ArrayList<Patient>();
    mLogger.d(response.toString());//w  w  w. ja  va  2s  .  c om

    try {
        JSONArray patientsJSONList = response.getJSONArray(BaseManager.RESULTS_KEY);
        for (int i = 0; i < patientsJSONList.length(); i++) {
            patientsList.add(PatientMapper.map(patientsJSONList.getJSONObject(i)));
        }

        refreshFragment(patientsList, FindPatientsActivity.FragmentMethod.Update);

    } catch (JSONException e) {
        mLogger.d(e.toString());
        refreshFragment(null, FindPatientsActivity.FragmentMethod.StopLoader);
    }
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;//  w  w w  .j ava2  s.c o  m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();

    if (title != null && title.length() > 0) {
        newTexts.add(title);
    }

    if (authors != null && !authors.isEmpty()) {
        boolean first = true;
        StringBuilder authorsText = new StringBuilder();
        for (String author : authors) {
            if (first) {
                first = false;
            } else {
                authorsText.append(", ");
            }
            authorsText.append(author);
        }
        newTexts.add(authorsText.toString());
    }

    if (pages != null && pages.length() > 0) {
        newTexts.add(pages + "pp.");
    }

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:org.godotengine.godot.Utils.java

public static Map<String, Object> jsonToMap(String jsonData) {
    JSONObject jobject = null;/*from ww  w  . j  ava 2  s . com*/

    try {
        jobject = new JSONObject(jsonData);
    } catch (JSONException e) {
        Utils.d("JSONObject exception: " + e.toString());
    }

    Map<String, Object> retMap = new HashMap<String, Object>();
    Iterator<String> keysItr = jobject.keys();

    while (keysItr.hasNext()) {
        try {
            String key = keysItr.next();
            Object value = jobject.get(key);

            retMap.put(key, value);
        } catch (JSONException e) {
            Utils.d("JSONObject get key error" + e.toString());
        }
    }

    return retMap;
}

From source file:com.krayzk9s.imgurholo.ui.ImagesFragment.java

public void onGetObject(Object object, String tag) {
    if (tag.equals(IMAGES)) {
        ImgurHoloActivity activity = (ImgurHoloActivity) getActivity();
        if (activity == null)
            return;
        SharedPreferences settings = activity.getApiCall().settings;
        JSONObject data = (JSONObject) object;
        Log.d("imagesData", "checking");
        Log.d("imagesData", "failed");
        JSONArray imageArray = new JSONArray();
        try {/*w w  w . ja va2  s . c o  m*/
            Log.d("URI", data.toString());
            imageArray = data.getJSONArray("data");
        } catch (JSONException e) {
            try {
                imageArray = data.getJSONObject("data").getJSONArray("images");
            } catch (JSONException e2) {
                Log.e("Error!", e2.toString() + data.toString());
            }
        }
        try {
            Boolean changed = false;
            for (int i = 0; i < imageArray.length(); i++) {
                JSONObject imageData = imageArray.getJSONObject(i);
                String s = "";
                if (isGridView)
                    s = settings.getString("IconQuality", "m");
                try {
                    if (imageData.has("is_album") && imageData.getBoolean("is_album")) {
                        if (!urls.contains("http://imgur.com/"
                                + imageData.getString(ImgurHoloActivity.IMAGE_DATA_COVER) + s + ".png")) {
                            changed = true;
                            urls.add("http://imgur.com/"
                                    + imageData.getString(ImgurHoloActivity.IMAGE_DATA_COVER) + s + ".png");
                            JSONParcelable dataParcel = new JSONParcelable();
                            dataParcel.setJSONObject(imageData);
                            ids.add(dataParcel);
                        }
                    } else {
                        if (!urls.contains("http://imgur.com/" + imageData.getString("id") + s + ".png")) {
                            changed = true;
                            urls.add("http://imgur.com/" + imageData.getString("id") + s + ".png");
                            JSONParcelable dataParcel = new JSONParcelable();
                            dataParcel.setJSONObject(imageData);
                            ids.add(dataParcel);
                        }
                    }
                } catch (RejectedExecutionException e) {
                    Log.e("Rejected", e.toString());
                }
            }
            fetchingImages = !changed;
        } catch (JSONException e) {
            Log.e("Error!", e.toString() + "here");
        }
        if (!isGridView && urls.size() > 0) {
            restoreCards();
        } else if (urls.size() > 0) {
            imageAdapter.notifyDataSetChanged();
        } else if (urls.size() == 0 && noImageView != null)
            noImageView.setVisibility(View.VISIBLE);
        else {
            fetchingImages = true;
        }
        if (mPullToRefreshLayout != null)
            mPullToRefreshLayout.setRefreshComplete();
        errorText.setVisibility(View.GONE);
    }
}

From source file:com.krayzk9s.imgurholo.ui.ImagesFragment.java

private void restoreCards() {
    try {//  w w w  .  j ava  2 s .co m
        ImgurHoloActivity activity = (ImgurHoloActivity) getActivity();
        int start = 0;
        if (cardListView != null && cardListView.getAdapter() != null)
            start = cardListView.getAdapter().getCount();
        if (cards == null) {
            cards = new ArrayList<Card>();
            mCardArrayAdapter = new CardArrayAdapter(getActivity(), cards);
            cardListView.setAdapter(mCardArrayAdapter);
        }
        for (int i = start; i < ids.size(); i++) {
            Card card = new Card(getActivity());
            final CustomHeaderInnerCard header = new CustomHeaderInnerCard(getActivity());
            header.setTitle(ids.get(i).getJSONObject().getString("title"));
            header.position = i;
            final ImagesFragment fragment = this;
            if (ids.get(i).getJSONObject().has("subreddit"))
                header.setPopupMenu(R.menu.card_image, new CardHeader.OnClickCardHeaderPopupMenuListener() {
                    @Override
                    public void onMenuItemClick(BaseCard card, MenuItem item) {
                        ImgurHoloActivity imgurHoloActivity = (ImgurHoloActivity) getActivity();
                        if (item.getTitle().equals(getString(R.string.rating_good)))
                            ImageUtils.upVote(fragment, ids.get(header.position), null, null,
                                    imgurHoloActivity.getApiCall());
                        if (item.getTitle().equals(getString(R.string.rating_bad)))
                            ImageUtils.downVote(fragment, ids.get(header.position), null, null,
                                    imgurHoloActivity.getApiCall());
                        if (item.getTitle().equals(getString(R.string.account)))
                            ImageUtils.gotoUser(fragment, ids.get(header.position));
                        if (item.getTitle().equals(getString(R.string.action_share)))
                            ImageUtils.shareImage(fragment, ids.get(header.position));
                        if (item.getTitle().equals(getString(R.string.action_copy)))
                            ImageUtils.copyImageURL(fragment, ids.get(header.position));
                        if (item.getTitle().equals(getString(R.string.action_download)))
                            ImageUtils.downloadImage(fragment, ids.get(header.position));
                        ImageUtils.updateImageFont(ids.get(header.position), header.scoreText);
                    }
                });
            else
                header.setPopupMenu(R.menu.card_image_no_account,
                        new CardHeader.OnClickCardHeaderPopupMenuListener() {
                            @Override
                            public void onMenuItemClick(BaseCard card, MenuItem item) {
                                ImgurHoloActivity imgurHoloActivity = (ImgurHoloActivity) getActivity();
                                if (item.getTitle().equals(getString(R.string.rating_good)))
                                    ImageUtils.upVote(fragment, ids.get(header.position), null, null,
                                            imgurHoloActivity.getApiCall());
                                if (item.getTitle().equals(getString(R.string.rating_bad)))
                                    ImageUtils.downVote(fragment, ids.get(header.position), null, null,
                                            imgurHoloActivity.getApiCall());
                                if (item.getTitle().equals(getString(R.string.account)))
                                    ImageUtils.gotoUser(fragment, ids.get(header.position));
                                if (item.getTitle().equals(getString(R.string.action_share)))
                                    ImageUtils.shareImage(fragment, ids.get(header.position));
                                if (item.getTitle().equals(getString(R.string.action_copy)))
                                    ImageUtils.copyImageURL(fragment, ids.get(header.position));
                                if (item.getTitle().equals(getString(R.string.action_download)))
                                    ImageUtils.downloadImage(fragment, ids.get(header.position));
                                ImageUtils.updateImageFont(ids.get(header.position), header.scoreText);
                            }
                        });
            card.addCardHeader(header);
            CustomThumbCard thumb = new CustomThumbCard(getActivity());
            thumb.setHeader(header);
            thumb.setExternalUsage(true);
            thumb.position = i;
            final int position = i;
            card.addCardThumbnail(thumb);
            if (!activity.getApiCall().settings.getString("theme", MainActivity.HOLO_LIGHT)
                    .equals(MainActivity.HOLO_LIGHT))
                card.setBackgroundResourceId(R.drawable.dark_card_background);
            CardView cardView = (CardView) getActivity().findViewById(R.id.list_cardId);
            card.setCardView(cardView);
            card.setOnClickListener(new Card.OnCardClickListener() {
                @Override
                public void onClick(Card card, View view) {
                    selectItem(position);
                }
            });
            cards.add(card);
        }
        mCardArrayAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        Log.e("Error!", e.toString());
    }
}

From source file:uk.org.rivernile.edinburghbustracker.server.livedata.LiveBusStopData.java

/**
 * Get all of the bus stop information available in this object and output
 * it in JSON format to the supplied Writer stream.
 *
 * @param out The stream to write the JSON text to.
 *///  ww w.  j av  a2s.com
public void writeJSONToStream(final Writer out) {
    if (out == null)
        throw new IllegalArgumentException("The Writer object" + " cannot be null.");

    JSONWriter jw = new JSONWriter(out);
    try {
        jw.object().key("stopCode").value(thisStopCode).key("stopName").value(thisStopName).key("services")
                .array();
        for (BusService s : busServices) {
            jw.object().key("serviceName").value(s.getServiceName()).key("route").value(s.getRoute())
                    .key("buses").array();
            for (LiveBus b : s.buses) {
                jw.object().key("destination").value(b.getDestination()).key("arrivalTime")
                        .value(b.getArrivalTime()).key("accessible").value(b.getAccessible()).endObject();
            }
            jw.endArray().endObject();
        }
        jw.endArray().endObject();
    } catch (JSONException e) {
        System.err.println("A JSON exception has occurred. The exception " + "reported was:");
        System.err.println(e.toString());
    }
}

From source file:com.altcanvas.asocial.Twitter.java

public JSONObject update(String status) throws AsocialException {
    HashMap<String, String> postParams = new HashMap<String, String>();
    postParams.put("status", status);
    postParams.put("source", SOURCE);

    setOAuth("POST", updateURL, postParams);

    try {/*from  w ww. ja  v a 2s . c  o m*/
        return new JSONObject(Http.post(updateURL, headers, postParams));
    } catch (HttpException he) {
        throw new AsocialException(he.responseCode, he.toString());
    } catch (JSONException je) {
        throw new AsocialException(AsocialException.JSONE, je.toString());
    } catch (IOException ioe) {
        throw new AsocialException(AsocialException.IOE, ioe.toString());
    }
}