Example usage for org.json JSONException printStackTrace

List of usage examples for org.json JSONException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.example.karspoolingapp.RouteByHitchhikerCar.java

public void addListenerOnButton() {

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

        @Override/* w w  w.j  a  v  a  2  s . c  o  m*/
        public void onClick(View v) {

            // get selected radio button from radioGroup
            int selectedId = rg.getCheckedRadioButtonId();

            System.out.println("selected Id is" + selectedId);

            try {
                JSONObject c = jsonTripDetails.getJSONObject(selectedId - 1);
                String parent_username_str = c.getString("username");
                String route = c.getString("route");
                String timing = c.getString("timing");
                String seating_capacity = c.getString("seating_capacity");
                String new_sp = c.getString("start_point");
                String new_dp = c.getString("end_point");

                System.out.println("before main method");

                new InsertToDatabase(username, parent_username_str, route, timing, seating_capacity, new_sp,
                        new_dp).execute();

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    });

}

From source file:app.hanks.com.conquer.activity.LoginActivity.java

/**
 * ?QQ?//from  www. j  a  v  a  2 s.  co m
 */
public void getQQInfo(final JSONObject obj) {
    // ?APPID??????
    // ?http://wiki.connect.qq.com/get_user_info??API??QQ????
    new Thread() {
        @Override
        public void run() {
            try {
                Map<String, String> params = new HashMap<String, String>();
                // ?json
                // {
                // "qq": {
                // "openid": "B4F5ABAD717CCC93ABF3BF28D4BCB03A",
                // "access_token": "05636ED97BAB7F173CB237BA143AF7C9",
                // "expires_in": 7776000
                // }
                // }
                if (obj != null) {
                    // params.put("access_token", obj.getJSONObject("qq")
                    // .getString("access_token"));//
                    // ???access_token
                    // params.put("uid",
                    // obj.getJSONObject("weibo").getString("uid"));//
                    // ???uid
                    params.put("access_token", obj.getJSONObject("qq").getString("access_token"));// QQ??access_token
                    params.put("openid", obj.getJSONObject("qq").getString("openid"));
                    params.put("oauth_consumer_key", Constants.QQ_KEY);// oauth_consumer_keyQQ???appid
                    params.put("format", "json");// ?--?
                }
                String result = NetUtils.getRequest("https://graph.qq.com/user/get_user_info", params);
                L.i("login", "QQ?" + result);
                JSONObject json = new JSONObject(result);
                nickName = json.getString("nickname");
                gender = json.getString("gender");
                photoUrl = json.getString("figureurl_qq_2").replace("\\", "");
                city = json.getString("province") + " " + json.getString("city");
                goDialogActivity();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

From source file:app.hanks.com.conquer.activity.LoginActivity.java

@Override
public void onComplete(Object o) {

    try {/*w w  w.jav  a 2s.co  m*/
        JSONObject jsonObject = new JSONObject(o.toString());
        String userId = jsonObject.getString("openid");
        String expiresIn = jsonObject.getString("expires_in");
        String accessToken = jsonObject.getString("access_token");
        BmobUser.BmobThirdUserAuth authInfo = new BmobUser.BmobThirdUserAuth("qq", accessToken, expiresIn,
                userId);
        BmobUser.loginWithAuthData(context, authInfo, new OtherLoginListener() {

            @Override
            public void onSuccess(JSONObject userAuth) {
                L.i("QQ??" + userAuth.toString());
                getQQInfo(userAuth);
            }

            @Override
            public void onFailure(int code, String msg) {
                // TODO Auto-generated method stub
                Log.i("smile", "" + msg);
            }

        });

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:weathernotificationservice.wns.activities.MainActivity.java

private ParseResult parseTodayJson(String result) {
    try {/*ww w . ja  v a  2s  .c om*/
        JSONObject reader = new JSONObject(result);

        final String code = reader.optString("cod");
        if ("404".equals(code)) {
            return ParseResult.CITY_NOT_FOUND;
        }

        String city = reader.getString("name");
        String country = "";
        JSONObject countryObj = reader.optJSONObject("sys");
        if (countryObj != null) {
            country = countryObj.getString("country");
            todayWeather.setSunrise(countryObj.getString("sunrise"));
            todayWeather.setSunset(countryObj.getString("sunset"));
        }
        todayWeather.setCity(city);
        todayWeather.setCountry(country);

        JSONObject coordinates = reader.getJSONObject("coord");
        if (coordinates != null) {
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
            sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon"))
                    .putFloat("longitude", (float) coordinates.getDouble("lat")).commit();
        }

        JSONObject main = reader.getJSONObject("main");

        todayWeather.setTemperature(main.getString("temp"));
        todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description"));
        JSONObject windObj = reader.getJSONObject("wind");
        todayWeather.setWind(windObj.getString("speed"));
        if (windObj.has("deg")) {
            todayWeather.setWindDirectionDegree(windObj.getDouble("deg"));
        } else {
            Log.e("parseTodayJson", "No wind direction available");
            todayWeather.setWindDirectionDegree(null);
        }
        todayWeather.setPressure(main.getString("pressure"));
        todayWeather.setHumidity(main.getString("humidity"));

        JSONObject rainObj = reader.optJSONObject("rain");
        String rain;
        if (rainObj != null) {
            rain = getRainString(rainObj);
        } else {
            JSONObject snowObj = reader.optJSONObject("snow");
            if (snowObj != null) {
                rain = getRainString(snowObj);
            } else {
                rain = "0";
            }
        }
        todayWeather.setRain(rain);

        final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id");
        todayWeather.setId(idString);
        todayWeather.setIcon(
                setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));

        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                .edit();
        editor.putString("lastToday", result);
        editor.commit();

    } catch (JSONException e) {
        Log.e("JSONException Data", result);
        e.printStackTrace();
        return ParseResult.JSON_EXCEPTION;
    }

    return ParseResult.OK;
}

From source file:weathernotificationservice.wns.activities.MainActivity.java

public ParseResult parseLongTermJson(String result) {
    int i;/*from   w  w w  .  j a  v a2 s .c  om*/
    try {
        JSONObject reader = new JSONObject(result);

        final String code = reader.optString("cod");
        if ("404".equals(code)) {
            if (longTermWeather == null) {
                longTermWeather = new ArrayList<>();
                longTermTodayWeather = new ArrayList<>();
                longTermTomorrowWeather = new ArrayList<>();
            }
            return ParseResult.CITY_NOT_FOUND;
        }

        longTermWeather = new ArrayList<>();
        longTermTodayWeather = new ArrayList<>();
        longTermTomorrowWeather = new ArrayList<>();

        JSONArray list = reader.getJSONArray("list");
        for (i = 0; i < list.length(); i++) {
            Weather weather = new Weather();

            JSONObject listItem = list.getJSONObject(i);
            JSONObject main = listItem.getJSONObject("main");

            weather.setDate(listItem.getString("dt"));
            weather.setTemperature(main.getString("temp"));
            weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
            JSONObject windObj = listItem.optJSONObject("wind");
            if (windObj != null) {
                weather.setWind(windObj.getString("speed"));
                weather.setWindDirectionDegree(windObj.getDouble("deg"));
            }
            weather.setPressure(main.getString("pressure"));
            weather.setHumidity(main.getString("humidity"));

            JSONObject rainObj = listItem.optJSONObject("rain");
            String rain = "";
            if (rainObj != null) {
                rain = getRainString(rainObj);
            } else {
                JSONObject snowObj = listItem.optJSONObject("snow");
                if (snowObj != null) {
                    rain = getRainString(snowObj);
                } else {
                    rain = "0";
                }
            }
            weather.setRain(rain);

            final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
            weather.setId(idString);

            final String dateMsString = listItem.getString("dt") + "000";
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(Long.parseLong(dateMsString));
            weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));

            Calendar today = Calendar.getInstance();
            if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
                longTermTodayWeather.add(weather);
            } else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
                longTermTomorrowWeather.add(weather);
            } else {
                longTermWeather.add(weather);
            }
        }
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                .edit();
        editor.putString("lastLongterm", result);
        editor.commit();
    } catch (JSONException e) {
        Log.e("JSONException Data", result);
        e.printStackTrace();
        return ParseResult.JSON_EXCEPTION;
    }

    return ParseResult.OK;
}

From source file:org.openhab.habdroid.model.OpenHABItem.java

public OpenHABItem(JSONObject jsonObject) {
    try {// w w  w. ja  va2 s . c o  m
        if (jsonObject.has("type"))
            this.setType(jsonObject.getString("type"));
        if (jsonObject.has("groupType"))
            this.setGroupType(jsonObject.getString("groupType"));
        if (jsonObject.has("name"))
            this.setName(jsonObject.getString("name"));
        if (jsonObject.has("state")) {
            if (jsonObject.getString("state").equals("NULL") || jsonObject.getString("state").equals("UNDEF")
                    || jsonObject.getString("state").equalsIgnoreCase("undefined")) {
                this.setState(null);
            } else {
                this.setState(jsonObject.getString("state"));
            }
        }
        if (jsonObject.has("link"))
            this.setLink(jsonObject.getString("link"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:nl.hnogames.domoticzapi.Parsers.ScenesParser.java

@Override
public void parseResult(String result) {

    try {//from  www .  j  a  va  2s  .  c om
        JSONArray jsonArray = new JSONArray(result);
        ArrayList<SceneInfo> mScenes = new ArrayList<>();

        if (jsonArray.length() > 0) {

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject row = jsonArray.getJSONObject(i);
                mScenes.add(new SceneInfo(row));
            }
        }

        if (idx == 999999)
            scenesReceiver.onReceiveScenes(mScenes);
        else {
            scenesReceiver.onReceiveScene(getScene(idx, mScenes));
        }

    } catch (JSONException e) {
        Log.e(TAG, "ScenesParser JSON exception");
        e.printStackTrace();
        scenesReceiver.onError(e);
    }
}

From source file:ui.frame.UILogin.java

public UILogin() {
    super("Login");

    Label l = new Label();

    setLayout(new BorderLayout());
    this.setPreferredSize(new Dimension(400, 300));

    Panel p = new Panel();

    loginPanel = p.createPanel(Layouts.grid, 4, 2);
    loginPanel.setBorder(new EmptyBorder(25, 25, 0, 25));
    lblUser = l.createLabel("Username:");
    lblPassword = l.createLabel("Password:");
    lblURL = l.createLabel("Server URL");
    lblBucket = l.createLabel("Bucket");

    tfURL = new JTextField();
    tfURL.setText("kaiup.kaisquare.com");
    tfBucket = new JTextField();
    PromptSupport.setPrompt("BucketName", tfBucket);
    tfUser = new JTextField();
    PromptSupport.setPrompt("Username", tfUser);
    pfPassword = new JPasswordField();
    PromptSupport.setPrompt("Password", pfPassword);

    buttonPanel = p.createPanel(Layouts.flow);
    buttonPanel.setBorder(new EmptyBorder(0, 0, 25, 0));
    Button b = new Button();
    JButton btnLogin = b.createButton("Login");
    JButton btnExit = b.createButton("Exit");
    btnLogin.setPreferredSize(new Dimension(150, 50));
    btnExit.setPreferredSize(new Dimension(150, 50));
    Component[] arrayBtn = { btnExit, btnLogin };
    p.addComponentsToPanel(buttonPanel, arrayBtn);

    Component[] arrayComponents = { lblURL, tfURL, lblBucket, tfBucket, lblUser, tfUser, lblPassword,
            pfPassword };/*ww  w.  j  a v a2s  .  c  om*/
    p.addComponentsToPanel(loginPanel, arrayComponents);
    add(loginPanel, BorderLayout.CENTER);
    add(buttonPanel, BorderLayout.SOUTH);
    pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    setVisible(true);
    btnLogin.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            SwingWorker<Void, Void> mySwingWorker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    if (tfUser.getText().equals("") || String.valueOf(pfPassword.getPassword()).equals("")
                            || tfBucket.getText().equals("")) {
                        JOptionPane.showMessageDialog(Data.mainFrame, "Please fill up all the fields", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    } else {
                        String username = tfUser.getText();
                        String password = String.valueOf(pfPassword.getPassword());
                        Data.URL = Data.protocol + tfURL.getText();
                        Data.targetURL = Data.protocol + tfURL.getText() + "/api/" + tfBucket.getText() + "/";

                        String response = api.loginBucket(Data.targetURL, username, password);

                        try {

                            if (DesktopAppMain.checkResult(response)) {
                                JSONObject responseJSON = new JSONObject(response);
                                Data.sessionKey = responseJSON.get("session-key").toString();
                                response = api.getUserFeatures(Data.targetURL, Data.sessionKey);
                                if (checkFeatures(response)) {
                                    Data.mainFrame = new KAIQRFrame();
                                    Data.mainFrame.uiInventorySelect = new UIInventorySelect();
                                    Data.mainFrame.addPanel(Data.mainFrame.uiInventorySelect, "inventory");
                                    Data.mainFrame.showPanel("inventory");
                                    Data.mainFrame.pack();
                                    setVisible(false);
                                    Data.mainFrame.setVisible(true);

                                } else {
                                    JOptionPane.showMessageDialog(Data.loginFrame,
                                            "User does not have necessary features", "Error",
                                            JOptionPane.ERROR_MESSAGE);
                                }
                            } else {
                                JOptionPane.showMessageDialog(Data.loginFrame, "Wrong username/password",
                                        "Error", JOptionPane.ERROR_MESSAGE);
                            }

                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }

                    return null;
                }
            };

            Window win = SwingUtilities.getWindowAncestor((AbstractButton) e.getSource());
            final JDialog dialog = new JDialog(win, "Login", ModalityType.APPLICATION_MODAL);

            mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {

                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (evt.getPropertyName().equals("state")) {
                        if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
                            dialog.dispose();
                        }
                    }
                }
            });

            mySwingWorker.execute();

            JProgressBar progressBar = new JProgressBar();
            progressBar.setIndeterminate(true);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(progressBar, BorderLayout.CENTER);
            panel.add(new JLabel("Logging in .........."), BorderLayout.PAGE_START);
            dialog.add(panel);
            dialog.pack();
            dialog.setBounds(50, 50, 300, 100);
            dialog.setLocationRelativeTo(Data.mainFrame);
            dialog.setVisible(true);
        }
    });

    btnExit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }

    });

}

From source file:ui.frame.UILogin.java

public static boolean checkFeatures(String response) {
    boolean result = false;
    HashMap<String, String> featureList = new HashMap<String, String>();
    JSONObject responseObject;//from   w w w.j  a va 2 s . com
    try {
        responseObject = new JSONObject(response);
        if (responseObject.get("result").equals("ok")) {
            JSONArray features = responseObject.getJSONArray("features");

            for (int i = 0; i < features.length(); i++) {
                JSONObject feature = features.getJSONObject(i);

                String featureName = feature.getString("name");

                if (featureName.equals("global-license-management")
                        || featureName.equals("inventory-management")
                        || featureName.equals("access-key-management")
                        || featureName.equals("bucket-management")) {
                    featureList.put(featureName, feature.getString("name"));
                }
            }

            if (featureList.size() == 4) {
                return true;
            }
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result;
}

From source file:org.apache.cordova.plugins.DownloadManager.DownloadManager.java

@Override
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) {
    if (action.equals("start")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    /* Get OPTIONS */
                    JSONObject params = args.getJSONObject(0);
                    String fileUrl = params.getString("url");
                    Boolean overwrite = params.getBoolean("overwrite");
                    String fileName = params.has("fileName") ? params.getString("fileName")
                            : fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                    String filePath = params.has("filePath") ? params.getString("filePath")
                            : cordova.getActivity()
                                    .getString(cordova.getActivity().getResources().getIdentifier("app_name",
                                            "string", cordova.getActivity().getPackageName()));
                    String startToast = params.has("startToast") ? params.getString("startToast")
                            : "Download Start!";
                    String ticker = params.has("ticker") ? params.getString("ticker") : "Downloading...";
                    String endToast = params.has("endToast") ? params.getString("endToast")
                            : "Download Complete!";
                    String cancelToast = params.has("cancelToast") ? params.getString("cancelToast")
                            : "Download canceled!";
                    Boolean useNotificationBar = params.has("useNotificationBar")
                            ? params.getBoolean("useNotificationBar")
                            : true;/*from ww w.java 2  s  .c o m*/
                    String notificationTitle = params.has("notificationTitle")
                            ? params.getString("notificationTitle")
                            : "Downloading: " + fileName;

                    String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/"
                            + filePath + "/";

                    // Get an ID:
                    int downloader_id = new Random().nextInt(10000);
                    String downloader_id_str = String.valueOf(downloader_id);

                    // Instantiate Downloader with the ID:
                    Downloader downloadFile = new Downloader(downloader_id_str, fileUrl, dirName, fileName,
                            overwrite, startToast, ticker, notificationTitle, endToast, cancelToast,
                            useNotificationBar, callbackContext, cordova, webView);
                    // Store ID: ATT! GLobal Here!
                    //DownloadControllerGlobals.ids.add(downloader_id_str);
                    downloading_ids.add(downloader_id_str);

                    // Start Download
                    downloadFile.run();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("PhoneGapLog",
                            "DownloaderMaganager Plugin: Error: " + PluginResult.Status.JSON_EXCEPTION);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.ERROR);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
                }
            }
        });
        return true;
    } else if (action.equals("cancel")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    JSONObject params = args.getJSONObject(0);
                    String cancelID = params.has("id") ? params.getString("id") : null;
                    Log.d("PhoneGapLog", "Este es el ID que me llega para cancelar: " + cancelID);

                    if (cancelID == null) {
                        callbackContext
                                .sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "ID not found"));
                    }
                    //if (DownloadControllerGlobals.ids.indexOf(cancelID) == -1) {
                    if (!downloading_ids.isId(cancelID)) {
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR,
                                "The id has no download associated"));
                    } else {
                        //DownloadControllerGlobals.ids.remove(DownloadControllerGlobals.ids.indexOf(cancelID));
                        downloading_ids.del(cancelID);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("PhoneGapLog",
                            "DownloaderMaganager Plugin: Error: " + PluginResult.Status.JSON_EXCEPTION);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                }
            }
        });
        return true;
    } else if (action.equals("isdownloading")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    JSONObject params = args.getJSONObject(0);
                    String cancelID = params.has("id") ? params.getString("id") : null;
                    Log.d("PhoneGapLog", "Este es el ID que me llega para cancelar: " + cancelID);

                    if (cancelID == null) {
                        callbackContext.sendPluginResult(
                                new PluginResult(PluginResult.Status.ERROR, "Error checking id"));
                    }
                    if (!downloading_ids.isId(cancelID)) {
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, false));
                    } else {
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("PhoneGapLog",
                            "DownloaderMaganager Plugin: Error: " + PluginResult.Status.JSON_EXCEPTION);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                }
            }
        });
        return true;
    } else {
        Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.INVALID_ACTION);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
        return false;
    }
}