Example usage for org.json JSONException getMessage

List of usage examples for org.json JSONException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:io.winch.phonegap.plugin.WinchPlugin.java

private void load(JSONArray args) {
    try {/*from   w ww  . ja va2  s.co  m*/
        List<LoadElement> loadElements = new ArrayList<LoadElement>();
        JSONObject params = args.getJSONObject(0);
        Iterator<?> iter = params.keys();

        // iterate to retrieve load pairs
        while (iter.hasNext()) {
            String namespace = (String) iter.next();
            String key = params.getString(namespace);
            LoadElement le = new LoadElement(namespace, key);
            loadElements.add(le);
        }

        mWinch.load(this, loadElements);
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (WinchError e) {
        e.printStackTrace();
        PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage());
        this.loadCallback.sendPluginResult(r);
    }
}

From source file:io.winch.phonegap.plugin.WinchPlugin.java

private void count(CallbackContext callbackContext, JSONArray args) {
    try {// www.j  ava2 s . c  om
        String namespace = args.getString(0);
        int count = mWinch.getNamespace(namespace).count();
        PluginResult r = new PluginResult(PluginResult.Status.OK, count);
        callbackContext.sendPluginResult(r);
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (WinchError e) {
        e.printStackTrace();
        PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage());
        callbackContext.sendPluginResult(r);
    }
}

From source file:io.winch.phonegap.plugin.WinchPlugin.java

private void put(CallbackContext callbackContext, CordovaArgs args) {
    try {//w  w w.ja  v  a  2  s . co m
        String namespace = args.getString(0);
        String key = args.getString(1);
        byte[] data = args.getArrayBuffer(2);

        mWinch.getNamespace(namespace).put(key, data);
        callbackContext.success();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (WinchError e) {
        e.printStackTrace();
        PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage());
        callbackContext.sendPluginResult(r);
    }
}

From source file:io.winch.phonegap.plugin.WinchPlugin.java

private void iterateAsString(final CallbackContext callbackContext, JSONArray args) {
    try {/*from   w w w.j  a  va2  s.  co  m*/
        String namespace = args.getString(0);
        Enumerator it1 = new Enumerator() {
            public int next() {
                JSONObject obj = new JSONObject();
                try {
                    obj.put(KEY, key);
                    obj.put(DATA, new String(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                PluginResult r = new PluginResult(PluginResult.Status.OK, obj);
                r.setKeepCallback(true);
                callbackContext.sendPluginResult(r);
                return Enumerator.Code.NONE;
            }
        };
        mWinch.getNamespace(namespace).enumerate(it1);
    } catch (JSONException e1) {
        e1.printStackTrace();
    } catch (WinchError e) {
        e.log();
        PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage());
        callbackContext.sendPluginResult(r);
    }

    PluginResult r = new PluginResult(PluginResult.Status.OK, false);
    r.setKeepCallback(false);
    callbackContext.sendPluginResult(r);
}

From source file:io.winch.phonegap.plugin.WinchPlugin.java

private void iterateAsBase64(final CallbackContext callbackContext, JSONArray args) {
    try {//from ww w  . j av  a  2s .co  m
        String namespace = args.getString(0);
        Enumerator it1 = new Enumerator() {
            public int next() {
                JSONObject obj = new JSONObject();
                try {
                    obj.put(KEY, key);
                    String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
                    obj.put(DATA, base64);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                PluginResult r = new PluginResult(PluginResult.Status.OK, obj);
                r.setKeepCallback(true);
                callbackContext.sendPluginResult(r);
                return Enumerator.Code.NONE;
            }
        };
        mWinch.getNamespace(namespace).enumerate(it1);
    } catch (JSONException e1) {
        e1.printStackTrace();
    } catch (WinchError e) {
        e.log();
        PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage());
        callbackContext.sendPluginResult(r);
    }

    PluginResult r = new PluginResult(PluginResult.Status.OK, false);
    r.setKeepCallback(false);
    callbackContext.sendPluginResult(r);
}

From source file:com.nokia.example.pepperfarm.iap.Payment.java

/**
 * Fetches the prices asynchronously// w w  w .  j a  v a2 s  .c  o m
 */
public void fetchPrices() {

    if (!isBillingAvailable())
        return;

    for (Product p : Content.ITEMS) {
        if (p.getPrice() != "") {
            Log.i("fetchPrices", "Prices already available. Not fetching.");
            return;
        }
    }

    AsyncTask<Void, String, Void> pricesTask = new AsyncTask<Void, String, Void>() {

        @Override
        protected Void doInBackground(Void... params) {

            ArrayList<String> productIdArray = new ArrayList<String>(Content.ITEM_MAP.keySet());
            Bundle productBundle = new Bundle();
            productBundle.putStringArrayList("ITEM_ID_LIST", productIdArray);

            try {
                Bundle priceInfo = npay.getProductDetails(API_VERSION, activity.getPackageName(),
                        ITEM_TYPE_INAPP, productBundle);

                if (priceInfo.getInt("RESPONSE_CODE", RESULT_ERR) == RESULT_OK) {
                    ArrayList<String> productDetailsList = priceInfo.getStringArrayList("DETAILS_LIST");

                    for (String productDetails : productDetailsList) {
                        parseProductDetails(productDetails);
                    }

                } else {
                    Log.e("fetchPrices", "PRICE - priceInfo was not ok: Result was: "
                            + priceInfo.getInt("RESPONSE_CODE", -100));
                }

            } catch (JSONException e) {
                Log.e("fetchPrices", "PRODUCT DETAILS PARSING EXCEPTION: " + e.getMessage(), e);
            } catch (RemoteException e) {
                Log.e("fetchPrices", "PRICE EXCEPTION: " + e.getMessage(), e);
            }
            return null;
        }

        private void parseProductDetails(String productDetails) throws JSONException {

            ProductDetails details = new ProductDetails(productDetails);

            Log.i("fetchPrices", productDetails);

            Product p = Content.ITEM_MAP.get(details.getProductId());

            if (p != null) {
                p.setPrice(details.getPriceFormatted());
                Log.i("fetchPrices", "PRICE RECEIVED - " + details.getPrice() + " " + details.getCurrency());
            } else {
                Log.i("fetchPrices",
                        "Unable to set price for product " + details.getProductId() + ". Product not found.");
            }
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (ProductListFragment.purchaseListAdapter != null) {
                ProductListFragment.purchaseListAdapter.notifyDataSetChanged();
            }
            if (MainScreenPepperListFragment.reference.adapter != null) {
                MainScreenPepperListFragment.reference.adapter.notifyDataSetChanged();
            }
        }

    };
    pricesTask.execute();
}

From source file:com.nokia.example.pepperfarm.iap.Payment.java

/**
 * Check the products that we have already purchased
 *//*from   www.j  av  a  2  s . c om*/
public void getPurchases(boolean ignoreLifeCycleCheck) {

    if (!isBillingAvailable())
        return;

    if (ignoreLifeCycleCheck == false) {
        if (purchases_asked) {
            Log.i("getPurchases", "Restorables already asked.");
            return;
        }
    }

    MainScreenPepperListFragment.getpeppers.setVisibility(View.INVISIBLE);
    MainScreenPepperListFragment.fetch_peppers_progressbar.setVisibility(View.VISIBLE);
    MainScreenPepperListFragment.fetching_peppers.setVisibility(View.VISIBLE);

    AsyncTask<Void, String, Void> restoreTask = new AsyncTask<Void, String, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            ArrayList<String> productIdArray = new ArrayList<String>(Content.ITEM_MAP.keySet());
            Bundle productBundle = new Bundle();
            productBundle.putStringArrayList("ITEM_ID_LIST", productIdArray);

            try {
                Bundle purchases = npay.getPurchases(API_VERSION, activity.getPackageName(), ITEM_TYPE_INAPP,
                        productBundle, null);
                Log.i("getPurchases",
                        "GET PURCHASES RESPONSE CODE: " + purchases.getInt("RESPONSE_CODE", RESULT_ERR));

                if (purchases.getInt("RESPONSE_CODE", RESULT_ERR) == RESULT_OK) {

                    ArrayList<String> purchaseDataList = purchases
                            .getStringArrayList("INAPP_PURCHASE_DATA_LIST");

                    for (String purchaseData : purchaseDataList) {
                        parsePurchaseData(purchaseData);
                    }
                    purchases_asked = true;
                } else {
                    Log.e("getPurchases", "GET PURCHASES - response was not ok: Result was: "
                            + purchases.getInt("RESPONSE_CODE", RESULT_ERR));
                }

            } catch (JSONException e) {
                Log.e("getPurchases", "PURCHASE DATA PARSING EXCEPTION: " + e.getMessage(), e);
            } catch (RemoteException e) {
                Log.e("getPurchases", "EXCEPTION: " + e.getMessage(), e);
            }
            return null;
        }

        private void parsePurchaseData(String purchaseData) throws JSONException {

            Purchase purchase = new Purchase(purchaseData);

            Product p = Content.ITEM_MAP.get(purchase.getProductId());

            if (p != null) {
                p.setPurchased(purchase);
                Log.i("getPurchases", "Restoring product " + purchase.getProductId() + " Purchase token: "
                        + purchase.getToken());
            } else {
                Log.i("getPurchases",
                        "Unable to restore product " + purchase.getProductId() + ". Product not found.");
            }

        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            MainScreenPepperListFragment.getpeppers.setVisibility(View.VISIBLE);
            MainScreenPepperListFragment.fetch_peppers_progressbar.setVisibility(View.GONE);
            MainScreenPepperListFragment.fetching_peppers.setVisibility(View.GONE);

            if (ProductListFragment.purchaseListAdapter != null) {
                ProductListFragment.purchaseListAdapter.notifyDataSetChanged();
            }
            if (MainScreenPepperListFragment.reference.adapter != null) {
                MainScreenPepperListFragment.reference.adapter.notifyDataSetChanged();
            }
        }

    };
    restoreTask.execute();
}

From source file:com.example.nestedarchetypeactivityexample.InnerArchetypeViewerActivity.java

private void setupButtonsListener() {
    Button butJson = (Button) findViewById(R.id.butJson);
    butJson.setOnClickListener(new OnClickListener() {

        @Override// w  ww.  ja v  a 2  s  .c om
        public void onClick(View v) {
            String content;
            try {
                content = getTemplateJsonContent().toString(2);
                showInfoDialog(content);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                showInfoDialog(String.format("Error Parsing Json Content: \n\n %s", e.getMessage()));
            }

        }
    });

    Button butSave = (Button) findViewById(R.id.butSave);
    butSave.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            submitTemplate();

        }
    });

    Button butReset = (Button) findViewById(R.id.butReset);
    butReset.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            resetTemplate();

        }
    });
}

From source file:com.facebook.login.GetTokenLoginMethodHandler.java

void complete(final LoginClient.Request request, final Bundle result) {
    String userId = result.getString(NativeProtocol.EXTRA_USER_ID);
    // If the result is missing the UserId request it
    if (userId == null || userId.isEmpty()) {
        loginClient.notifyBackgroundProcessingStart();

        String accessToken = result.getString(NativeProtocol.EXTRA_ACCESS_TOKEN);
        Utility.getGraphMeRequestWithCacheAsync(accessToken, new Utility.GraphMeRequestWithCacheCallback() {
            @Override/*from   w w  w.  j a v  a 2s.  c  o  m*/
            public void onSuccess(JSONObject userInfo) {
                try {
                    String userId = userInfo.getString("id");
                    result.putString(NativeProtocol.EXTRA_USER_ID, userId);
                    onComplete(request, result);
                } catch (JSONException ex) {
                    loginClient.complete(LoginClient.Result.createErrorResult(loginClient.getPendingRequest(),
                            "Caught exception", ex.getMessage()));
                }
            }

            @Override
            public void onFailure(FacebookException error) {
                loginClient.complete(LoginClient.Result.createErrorResult(loginClient.getPendingRequest(),
                        "Caught exception", error.getMessage()));
            }
        });
    } else {
        onComplete(request, result);
    }

}

From source file:org.openhab.io.myopenhab.internal.MyOpenHABClient.java

private void handleRequestEvent(JSONObject data) {
    try {/*from w ww.ja v a  2 s .c  o m*/
        // Get myOH unique request Id
        int requestId = data.getInt("id");
        logger.debug("Got request {}", requestId);
        // Get request path
        String requestPath = data.getString("path");
        // Get request method
        String requestMethod = data.getString("method");
        // Get request body
        String requestBody = data.getString("body");
        // Get JSONObject for request headers
        JSONObject requestHeadersJson = data.getJSONObject("headers");
        logger.debug(requestHeadersJson.toString());
        // Get JSONObject for request query parameters
        JSONObject requestQueryJson = data.getJSONObject("query");
        // Create URI builder with base request URI of openHAB and path from request
        String newPath = URIUtil.addPaths(localBaseUrl, requestPath);
        @SuppressWarnings("unchecked")
        Iterator<String> queryIterator = requestQueryJson.keys();
        // Add query parameters to URI builder, if any
        newPath += "?";
        while (queryIterator.hasNext()) {
            String queryName = queryIterator.next();
            newPath += queryName;
            newPath += "=";
            newPath += URLEncoder.encode(requestQueryJson.getString(queryName), "UTF-8");
            if (queryIterator.hasNext())
                newPath += "&";
        }
        // Finally get the future request URI
        URI requestUri = new URI(newPath);
        // All preparations which are common for different methods are done
        // Now perform the request to openHAB
        // If method is GET
        logger.debug("Request method is " + requestMethod);
        Request request = jettyClient.newRequest(requestUri);
        setRequestHeaders(request, requestHeadersJson);
        request.header("X-Forwarded-Proto", "https");
        if (requestMethod.equals("GET")) {
            request.method(HttpMethod.GET);
        } else if (requestMethod.equals("POST")) {
            request.method(HttpMethod.POST);
            request.content(new BytesContentProvider(requestBody.getBytes()));
        } else if (requestMethod.equals("PUT")) {
            request.method(HttpMethod.PUT);
            request.content(new BytesContentProvider(requestBody.getBytes()));
        } else {
            // TODO: Reject unsupported methods
            logger.error("Unsupported request method " + requestMethod);
            return;
        }
        ResponseListener listener = new ResponseListener(requestId);
        request.onResponseHeaders(listener).onResponseContent(listener).onRequestFailure(listener)
                .send(listener);
        // If successfully submitted request to http client, add it to the list of currently
        // running requests to be able to cancel it if needed
        runningRequests.put(requestId, request);
    } catch (JSONException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
    }
}