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:produvia.com.scanner.DevicesActivity.java

/*********************************************************************
 * The WeaverSdk callback indicating that a task update occurred.
 * for example, a new service was discovered in the current network:
 *********************************************************************/
@Override//from  w ww .  ja va 2  s.  c  om
public void onTaskUpdate(int flag, JSONObject response) {
    if (response == null || mActivityPaused)
        return;
    try {
        //this flag indicates that a new service was discovered in the scan:
        if (flag == WeaverSdk.ACTION_SERVICES_SCAN) {
            if (response.getBoolean("success")) {
                handleReceivedServices(response.getJSONObject("data"));
            }
        }
        //when tha scan is running - it'll provide general state information from time to time:
        else if (flag == WeaverSdk.ACTION_SCAN_STATUS) {
            if (response.getBoolean("success")) {
                if (response.getString("info").equals("Scan running")) {
                    mLastScanStartedAt = Calendar.getInstance();
                    showScanProgress(true);
                } else {
                    mScanCycleCounter += 1;
                    showScanProgress(false);
                    //if we haven't found any light services - we'll show an error message:
                    //if we finished the scan - check if we found any devices:
                    if (mScanCycleCounter > 0 && (mDevices == null || mDevices.size() <= 0)) {
                        setErrorMessage(
                                "Weaver didn't detect any services in the network\nPlease make sure you're connected to the wifi\nand restart the app");
                        //stop the scan:
                        WeaverSdkApi.discoveryService(null, false);
                        return;
                    }
                    //stop the discovery service after max scan cycles:
                    if (mScanCycleCounter >= MAX_SCAN_CYCLES)
                        WeaverSdkApi.discoveryService(null, false);

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

}

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

public void promptLogin(final JSONObject loginService, final JSONObject responseData) {

    runOnUiThread(new Runnable() {
        public void run() {
            try {
                String type = loginService.getString("type");
                //there was a login error. login again
                if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_NORMAL)) {
                    //prompt for username and password and retry:
                    promptUsernamePassword(loginService, responseData, false, null);

                } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_KEY)) {

                    promptUsernamePassword(loginService, responseData, true,
                            loginService.getString("description"));

                } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_PRESS2LOGIN)) {
                    //prompt for username and password and retry:
                    int countdown = loginService.has("login_timeout") ? loginService.getInt("login_timeout")
                            : 15;//w  ww  . j a  va2  s . co m
                    final AlertDialog alertDialog = new AlertDialog.Builder(DevicesActivity.this).create();
                    alertDialog.setTitle(loginService.getString("description"));
                    alertDialog.setCancelable(false);
                    alertDialog.setCanceledOnTouchOutside(false);
                    alertDialog.setMessage(loginService.getString("description") + "\n"
                            + "Attempting to login again in " + countdown + " seconds...");
                    alertDialog.show(); //

                    new CountDownTimer(countdown * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            try {
                                alertDialog.setMessage(loginService.getString("description") + "\n"
                                        + "Attempting to login again in " + millisUntilFinished / 1000
                                        + " seconds...");
                            } catch (JSONException e) {

                            }
                        }

                        @Override
                        public void onFinish() {
                            alertDialog.dismiss();
                            new Thread(new Runnable() {
                                public void run() {

                                    try {
                                        JSONArray services = new JSONArray();
                                        services.put(loginService);
                                        responseData.put("services", services);
                                        WeaverSdkApi.servicesSet(DevicesActivity.this, responseData);
                                    } catch (JSONException e) {

                                    }
                                }
                            }).start();

                        }
                    }.start();

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

        }

    });

}

From source file:com.harmazing.aixiumama.model.sina.models.Geo.java

public static Geo parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }//from  w  ww  .ja  v  a 2 s.  c o  m

    Geo geo = null;
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        geo = parse(jsonObject);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return geo;
}

From source file:net.idlesoft.android.apps.github.activities.CommitsList.java

@Override
protected void onStart() {
    super.onStart();

    FlurryAgent.onStartSession(this, "K8C93KDB2HH3ANRDQH1Z");

    ((ListView) findViewById(R.id.lv_commits_list_list)).setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(final AdapterView<?> parent, final View v, final int position, final long id) {
            try {
                final Intent i = new Intent(CommitsList.this, Commit.class);
                i.putExtra("committer",
                        mCommitsJSON.getJSONObject(position).getJSONObject("committer").getString("login"));
                i.putExtra("author",
                        mCommitsJSON.getJSONObject(position).getJSONObject("author").getString("login"));
                i.putExtra("commit_sha", mCommitsJSON.getJSONObject(position).getString("id"));
                i.putExtra("repo_name", mRepoName);
                i.putExtra("repo_owner", mRepoOwner);
                CommitsList.this.startActivity(i);
            } catch (final JSONException e) {
                e.printStackTrace();
            }/*  w  w w .j a  va  2s . c o m*/
        }
    });
}

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);
    }/*from  w ww.j  a va  2s. c om*/
    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:damo.three.ie.prepay.InternetAddonAlarmManagerReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences sharedPrefsUsages = context.getSharedPreferences("damo.three.ie.previous_usage",
            Context.MODE_PRIVATE);
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);

    boolean notificationsEnabled = sharedPrefs.getBoolean("notification", true);
    String usages = sharedPrefsUsages.getString("usage_info", null);

    // first check if anything was persisted
    if (usages != null) {
        try {//from w ww  .j a  va2  s . co  m
            List<UsageItem> usageItems = JSONUtils.jsonToUsageItems(new JSONArray(usages));
            List<BasicUsageItem> basicUsageItems = UsageUtils.getAllBasicItems(usageItems);
            UsageUtils.registerInternetExpireAlarm(context, basicUsageItems, notificationsEnabled, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.example.klaudia.myapplication.Searcher.java

public JSONObject getJSONObjectFromArray(int index) {
    JSONObject result = null;/*from  w w w . j a  va2  s  .c  om*/
    try {
        if (recipesJSONArray.getJSONObject(index).has("vegan"))
            result = recipesJSONArray.getJSONObject(index);

        else {
            int recipceIndex = recipesJSONArray.getJSONObject(index).getInt("id");
            result = getRecipeJSONObjectById(recipceIndex);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.github.akinaru.bleanalyzer.bluetooth.connection.BluetoothDeviceConn.java

/**
 * Build Bluetooth device connection//from w ww  . j a v  a  2  s .com
 *
 * @param address
 */
@SuppressLint("NewApi")
public BluetoothDeviceConn(String address, String deviceName, final IBluetoothCustomManager manager) {
    this.deviceAddr = address;
    this.deviceName = deviceName;
    this.manager = manager;

    gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

            if (newState == BluetoothProfile.STATE_CONNECTED) {

                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" + gatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                connected = false;
                Log.i(TAG, "Disconnected from GATT server.");

                try {
                    JSONObject object = new JSONObject();
                    object.put(JsonConstants.BT_ADDRESS, getAddress());
                    object.put(JsonConstants.BT_DEVICE_NAME, getDeviceName());

                    ArrayList<String> values = new ArrayList<String>();
                    values.add(object.toString());

                    //when device is fully intitialized broadcast service discovery
                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCONNECTED, values);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (manager.getWaitingMap().containsKey(deviceAddr)) {
                    manager.getWaitingMap().get(deviceAddr).cancel(true);
                    manager.getWaitingMap().remove(deviceAddr);
                }

                if (BluetoothDeviceConn.this.gatt != null) {
                    Log.i(TAG, "connection close clean");
                    BluetoothDeviceConn.this.gatt.close();
                }
            }
        }

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {

            if (status == BluetoothGatt.GATT_SUCCESS) {

                Runnable test = new Runnable() {
                    @Override
                    public void run() {

                        //you can improve this by using reflection
                        device = new RfduinoDevice(BluetoothDeviceConn.this);

                        device.addInitListener(new IDeviceInitListener() {
                            @Override
                            public void onInit() {
                                try {
                                    JSONObject object = new JSONObject();
                                    object.put(JsonConstants.BT_ADDRESS, getAddress());
                                    object.put(JsonConstants.BT_DEVICE_NAME, getDeviceName());

                                    ArrayList<String> values = new ArrayList<String>();
                                    values.add(object.toString());

                                    connected = true;
                                    //when device is fully intitialized broadcast service discovery
                                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_CONNECTED,
                                            values);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        device.init();
                    }
                };
                Thread testThread = new Thread(test);
                testThread.start();

            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            //manager.getEventManager().set();
            if (device != null) {
                device.notifyCharacteristicWriteReceived(characteristic);
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            manager.getEventManager().set();
            if (device != null) {
                Log.i(TAG, "onCharacteristicRead");
                device.notifyCharacteristicReadReceived(characteristic);
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            manager.getEventManager().set();
        }

        @Override
        // Characteristic notification
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            manager.getEventManager().set();
            if (device != null) {
                Log.i(TAG, "onCharacteristicChanged");
                device.notifyCharacteristicChangeReceived(characteristic);
            }
        }
    };
}

From source file:com.timrae.rikaidroid.MainActivity.java

private void addKuromojiWebItems(StringBuilder builder, JSONArray tokens) {
    for (int i = 0; i < tokens.length(); i++) {
        String reading;/*www .j  a v  a 2s  . co m*/
        String surface;
        try {
            JSONObject token = tokens.getJSONObject(i);
            //base = token.getString("base");
            reading = token.getString("reading");
            surface = token.getString("surface");

            String formattedText;
            if (hasKanji(surface)) {
                // Try to join the surface form with any particles following it
                if (i < tokens.length() - 1) {
                    JSONObject nextToken = tokens.getJSONObject(i);
                    String pos = nextToken.getString("pos");
                    if (pos.contains("") || pos.contains("")) {
                        surface += nextToken.getString("surface");
                        i++;
                    }
                }
                formattedText = makeFurigana(surface, katToHira(reading));
                if (isAedictPresent(this)) {
                    formattedText = String.format(INTENT_URL, token.getString("base"), formattedText);
                }
            } else {
                formattedText = surface;
            }

            builder.append(formattedText);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.zxing.qrcode.decoding.CaptureActivityHandler.java

@Override
public void handleMessage(Message message) {
    switch (message.what) {
    case R.id.auto_focus:
        // Log.d(TAG, "Got auto-focus message");
        // When one auto focus pass finishes, start another. This is the
        // closest thing to
        // continuous AF. It does seem to hunt a bit, but I'm not sure what
        // else to do.
        if (state == State.PREVIEW) {
            CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
        }//from ww  w  . j a  va2s . co m
        break;
    case R.id.restart_preview:
        Log.d(TAG, "Got restart preview message");
        restartPreviewAndDecode();
        break;
    case R.id.decode_succeeded:
        Log.d(TAG, "Got decode succeeded message");
        state = State.SUCCESS;
        Bundle bundle = message.getData();
        Bitmap barcode = bundle == null ? null : (Bitmap) bundle.getParcelable(DecodeThread.BARCODE_BITMAP);
        final String str_result = ((Result) message.obj).getText();
        System.out.println("====str_result====" + str_result);
        String match = "^[0-9]{13}";
        boolean b = str_result.matches(match);
        // Toast.makeText(activity, ""+b, 1).show();
        // activity.handleDecode((Result) message.obj, barcode);
        if (b) {
            String url = RequestUrls.TIAOXING_CODE_URL.replace("[code]", str_result);
            FinalHttp fh = new FinalHttp();
            fh.get(url, new AjaxCallBack<Object>() {
                @Override
                public void onSuccess(Object t) {
                    // TODO Auto-generated method stub
                    super.onSuccess(t);
                    try {

                        System.out.println("===TIAOXING_CODE_URL====" + new JSONObject(t.toString()));
                        Intent tagIntent = new Intent(activity, TagdetialActivity.class);
                        tagIntent.putExtra("jsonStr", t.toString());
                        tagIntent.putExtra("barcodes", str_result);
                        tagIntent.putExtra("eid", eid);
                        tagIntent.putExtra("tag_ids", tag_ids);
                        activity.startActivity(tagIntent);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Throwable t, String strMsg) {
                    // TODO Auto-generated method stub
                    super.onFailure(t, strMsg);
                }
            });
        } else {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                // //// intent.setPackage("com.tencent.mm");//
                intent.putExtra(Intent.EXTRA_SUBJECT, "share");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // // 
                // intent.setData(Uri.parse("http://weixin.qq.com/r/o3w_sRvEMSVOhwrSnyCH"));
                intent.setData(Uri.parse(str_result));
                activity.startActivity(intent);
            } catch (Exception e) {
                Toast.makeText(activity, R.string.no_wechat_rem, Toast.LENGTH_SHORT).show();
            }
        }

        break;
    case R.id.decode_failed:
        // We're decoding as fast as possible, so when one decode fails,
        // start another.
        state = State.PREVIEW;
        CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
        break;
    case R.id.return_scan_result:
        Log.d(TAG, "Got return scan result message");
        activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
        activity.finish();
        break;
    }
}