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:com.polyvi.xface.extension.advancedfiletransfer.XFileUploader.java

@Override
public void onError(int errorCode) {
    setState(INIT);//from w  w  w .j  ava2 s. c o  m
    JSONObject error = new JSONObject();
    Status status = Status.ERROR;
    try {
        error.put("code", errorCode);
        error.put("source", mFilePath);
        error.put("target", mServer);
    } catch (JSONException e) {
        status = Status.JSON_EXCEPTION;
        XLog.e(CLASS_NAME, e.getMessage());
    }
    XExtensionResult result = new XExtensionResult(status, error);
    mCallbackCtx.sendExtensionResult(result);
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.XFileUploader.java

@Override
public void onProgressUpdated(int completeSize, long totalSize) {
    JSONObject jsonObj = new JSONObject();
    Status status = Status.PROGRESS_CHANGING;
    try {/*from w w  w  . j  a v  a2s .  c  om*/
        jsonObj.put("loaded", completeSize);
        jsonObj.put("total", totalSize);
    } catch (JSONException e) {
        status = Status.JSON_EXCEPTION;
        XLog.e(CLASS_NAME, e.getMessage());
    }
    XExtensionResult result = new XExtensionResult(status, jsonObj);
    result.setKeepCallback(true);
    mCallbackCtx.sendExtensionResult(result);
}

From source file:org.loklak.api.iot.ImportProfileServlet.java

private void doUpdate(Query post, HttpServletResponse response) throws IOException {
    String callback = post.get("callback", null);
    boolean jsonp = callback != null && callback.length() > 0;
    String data = post.get("data", "");
    if (data == null || data.length() == 0) {
        response.sendError(400, "your request must contain a data object.");
        return;// w ww  . j a  v  a  2  s. c  om
    }

    // parse the json data
    boolean success;

    try {
        JSONObject json = null;
        try {
            json = new JSONObject(data);
        } catch (JSONException e) {
        }
        if (json == null) {
            throw new IOException("cannot parse json");
        }
        if (!json.has("id_str")) {
            throw new IOException("id_str field missing");
        }
        if (!json.has("source_type")) {
            throw new IOException("source_type field missing");
        }
        ImportProfileEntry i = DAO.SearchLocalImportProfiles(json.getString("id_str"));
        if (i == null) {
            throw new IOException("import profile id_str field '" + json.getString("id_str") + "' not found");
        }
        ImportProfileEntry importProfileEntry;
        try {
            importProfileEntry = new ImportProfileEntry(json);
        } catch (IllegalArgumentException e) {
            response.sendError(400, "Error updating import profile : " + e.getMessage());
            return;
        }
        importProfileEntry.setLastModified(new Date());
        success = DAO.writeImportProfile(importProfileEntry, true);
    } catch (IOException | NullPointerException e) {
        response.sendError(400, "submitted data is invalid : " + e.getMessage());
        Log.getLog().warn(e);
        return;
    }

    post.setResponse(response, "application/javascript");
    JSONObject json = new JSONObject(true);
    json.put("status", "ok");
    json.put("records", success ? 1 : 0);
    json.put("message", "updated");
    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(json.toString(2));
    if (jsonp)
        sos.println(");");
    sos.println();
    post.finalize();
}

From source file:com.phonegap.plugin.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject //w w w .j a  v a2  s  . com
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // Create dialog in new thread 
    Runnable runnable = new Runnable() {
        public void run() {
            dialog = new Dialog(ctx.getContext(), android.R.style.Theme_Translucent_NoTitleBar);

            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams forwardParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, 1.0f);
            LinearLayout.LayoutParams closeParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams wvParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT);

            LinearLayout main = new LinearLayout(ctx.getContext());
            main.setOrientation(LinearLayout.VERTICAL);

            LinearLayout toolbar = new LinearLayout(ctx.getContext());
            toolbar.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            toolbar.setOrientation(LinearLayout.HORIZONTAL);

            ImageButton back = new ImageButton(ctx.getContext());
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });
            back.setId(1);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setLayoutParams(backParams);

            ImageButton forward = new ImageButton(ctx.getContext());
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });
            forward.setId(2);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setLayoutParams(forwardParams);

            edittext = new EditText(ctx.getContext());
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });
            edittext.setId(3);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setLayoutParams(editParams);

            ImageButton close = new ImageButton(ctx.getContext());
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });
            close.setId(4);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setLayoutParams(closeParams);

            webview = new WebView(ctx.getContext());
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(5);
            webview.setInitialScale(0);
            webview.setLayoutParams(wvParams);
            webview.requestFocus();
            webview.requestFocusFromTouch();

            toolbar.addView(back);
            toolbar.addView(forward);
            toolbar.addView(edittext);
            toolbar.addView(close);

            if (getShowLocationBar()) {
                main.addView(toolbar);
            }
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = ctx.getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.ctx.runOnUiThread(runnable);
    return "";
}

From source file:net.practicaldeveloper.phonegap.plugins.SmsPlugin.java

@Override
public PluginResult execute(String action, JSONArray arg1, String callbackId) {
    PluginResult result = new PluginResult(Status.INVALID_ACTION);

    if (action.equals(ACTION_SEND_SMS)) {
        try {// w w  w  .  j a  va2s  .  co m
            String phoneNumber = arg1.getString(0);
            String message = arg1.getString(1);
            sendSMS(phoneNumber, message);
            result = new PluginResult(Status.OK);
        } catch (JSONException ex) {
            result = new PluginResult(Status.JSON_EXCEPTION, ex.getMessage());
        }
    }

    return result;
}

From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java

@Override
public Collection<PointOfInterest> read() {
    final Collection<PointOfInterest> pois;

    try {/*from   w  w w . ja  v a2 s  .co m*/
        JSONObject geoJson = new JSONObject(geoJsonString);

        String type = geoJson.getString("type");

        if (type.equals("FeatureCollection")) {
            pois = fromFeatureCollection(geoJson.getJSONArray("features"));
        } else if (type.equals("GeometryCollection")) {
            pois = fromGeometryCollection(geoJson.getJSONArray("geometries"));
        } else {
            throw new IllegalArgumentException("GeoJson of unknown type");
        }
    } catch (JSONException e) {
        throw new IllegalArgumentException(e.getMessage());
    }

    return pois;
}

From source file:org.skt.runtime.html5apis.Battery.java

/**
 * Creates a JSONObject with the current battery information
 * /*w  w w  . j  a  va 2 s . co m*/
 * @param batteryIntent the current battery information
 * @return a JSONObject containing the battery status information
 */
private JSONObject getBatteryInfo(Intent batteryIntent) {
    JSONObject obj = new JSONObject();
    try {
        obj.put("level", batteryIntent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, 0));
        obj.put("charging",
                batteryIntent.getIntExtra(android.os.BatteryManager.EXTRA_PLUGGED, -1) > 0 ? true : false);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return obj;
}

From source file:produvia.com.scanner.DevicesActivity.java

private void updateServiceDeviceDatabase(JSONObject data) {
    try {//from www  .j a v  a2s  .  c  om
        //first add the services to the devices:
        JSONArray services = data.getJSONArray("services");
        for (int i = 0; i < services.length(); i++) {
            JSONObject service = services.getJSONObject(i);
            String device_id = service.getString("device_id");
            JSONObject device = data.getJSONObject("devices_info").getJSONObject(device_id);
            if (!device.has("services"))
                device.put("services", new JSONObject());
            device.getJSONObject("services").put(service.getString("id"), service);
        }

        JSONObject devices = data.getJSONObject("devices_info");
        //loop over the devices and merge them into the device display:
        for (Iterator<String> iter = devices.keys(); iter.hasNext();) {
            String device_id = iter.next();
            JSONObject device = devices.getJSONObject(device_id);
            //if a device card is already present - just merge the data:
            boolean found = false;
            int network_card_idx = -1;
            for (int i = 0; i < mDevices.size(); i++) {
                CustomListItem cli = mDevices.get(i);
                if (cli instanceof DeviceCard && ((DeviceCard) cli).getId().equals(device_id)) {
                    ((DeviceCard) cli).updateInfo(device);
                    found = true;
                    break;
                } else if (cli.getDescription().equals(device.getString("network_id"))) {
                    network_card_idx = i;
                }
            }

            if (!found) {
                if (network_card_idx < 0) {
                    JSONObject network = data.getJSONObject("networks_info")
                            .getJSONObject(device.getString("network_id"));
                    String name = "";
                    if (network.has("name") && network.getString("name") != null)
                        name = network.getString("name");
                    network_card_idx = addNetworkCard(name, device.getString("network_id"),
                            network.getBoolean("user_inside_network"));
                }
                network_card_idx += 1;
                //find the correct index for the card sorted by last seen:
                for (; network_card_idx < mDevices.size(); network_card_idx++) {
                    CustomListItem cli = mDevices.get(network_card_idx);
                    if (!(cli instanceof DeviceCard))
                        break;
                    if (((DeviceCard) cli).getLastSeen()
                            .compareTo(DeviceCard.getLastSeenFromString(device.getString("last_seen"))) < 0)
                        break;
                }

                DeviceCard dc = new DeviceCard(device);
                mDevices.add(network_card_idx, dc);
            }
        }
        notifyDataSetChanged();

    } catch (JSONException e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:com.example.hbranciforte.trafficclient.DataTraffic.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_data_traffic);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }// www.  jav  a2  s.  c o  m
    try {
        zone_info = new JSONObject((String) getIntent().getSerializableExtra("zone_info"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    EditText ed_fichas = (EditText) findViewById(R.id.fichas);
    ed_fichas.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            //float price = (float) 0.0;
            Integer time = 0;
            TextView txtvalor = (TextView) findViewById(R.id.valor);
            TextView txttiempo = (TextView) findViewById(R.id.txtTime);
            if (s.toString() != "") {
                try {
                    price = (float) zone_info.getDouble("unit_price") * Float.valueOf(s.toString());
                    time = zone_info.getInt("unit_time") * Integer.parseInt(s.toString());
                    txtvalor.setText("$ ".concat(Float.toString(price)));
                    txttiempo.setText(time.toString().concat(" min"));
                } catch (Exception e) {
                    Log.e("getting data0:", e.getMessage());
                    txttiempo.setText("0 min");
                    txtvalor.setText("$ 0.0");

                }
            }
        }
    });
}

From source file:com.example.hbranciforte.trafficclient.DataTraffic.java

private JSONObject getPaymentInfo() {
    JSONObject payment = new JSONObject();
    EditText paymentField1 = (EditText) findViewById(R.id.payment_field1);
    EditText licenseSec = (EditText) findViewById(R.id.payment_security);
    TextView valor = (TextView) findViewById(R.id.valor);
    try {// w  w  w.j  ava  2  s. co  m
        payment.put("type", "test_method");
        payment.put("data",
                "{\"data\",\"".concat(paymentField1.getText().toString()).concat("\",\"security\":\"")
                        .concat(licenseSec.getText().toString().concat("\",\"price\":")
                                .concat(Float.toString(price)).concat("}")));
        payment.put("price", price);
        return payment;
    } catch (JSONException e) {
        Log.e("json error", e.getMessage());
    }
    return payment;
}