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.intel.xdk.facebook.IntelXDKFacebook.java

@JavascriptInterface
public void showAppRequestDialog(final String parameters) {
    if (!session.isOpened()) {
        currentCommand = APP_REQUEST_DIALOG;
        currentCommandArguments = new String[] { parameters };
        login(defaultLoginPermissions);//from   ww  w  . j a v a2  s . co m
        return;
    } else {
        //busy=true;
    }

    activity.runOnUiThread(new Runnable() {
        //@Override
        public void run() {

            JSONObject json = new JSONObject();
            try {
                json = new JSONObject(parameters);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Bundle params = JSONtoBundle(json);

            params.putString("frictionless", useFrictionless);

            WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(activity, session, params))
                    .setOnCompleteListener(new OnCompleteListener() {

                        @Override
                        public void onComplete(Bundle values, FacebookException error) {
                            if (error != null) {
                                if (error instanceof FacebookOperationCanceledException) {
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                } else {
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                                            error.toString());
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                }
                            } else {
                                final String requestId = values.getString("request");
                                if (requestId != null) {
                                    JSONObject jsonData = BundleToJSON(values);
                                    String extra = "";

                                    try {
                                        String request = jsonData.getString("request");
                                        extra += "e.request=" + request + ";";
                                    } catch (JSONException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }

                                    int index = 0;
                                    if (jsonData.has("to[" + index + "]")) {
                                        extra += "e.to=[";
                                        while (jsonData.has("to[" + index + "]")) {
                                            try {
                                                extra += jsonData.getString("to[" + index + "]") + ",";
                                            } catch (JSONException e) {
                                            }
                                            index++;
                                        }
                                        extra += "];";
                                    }

                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=true;e.error='';e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}%sdocument.dispatchEvent(e);",
                                            jsonData.toString(), extra);
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                } else {
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                }
                            }
                        }

                    }).build();
            requestsDialog.show();
        }
    });

}

From source file:com.intel.xdk.facebook.IntelXDKFacebook.java

@JavascriptInterface
public void showNewsFeedDialog(final String parameters) {
    if (!session.isOpened()) {
        currentCommand = NEWS_FEED_DIALOG;
        currentCommandArguments = new String[] { parameters };
        login(defaultLoginPermissions);/*from   w w  w .  j av  a2 s  .co  m*/
        return;
    } else {
        busy = true;
    }

    activity.runOnUiThread(new Runnable() {
        //@Override
        public void run() {

            JSONObject json = new JSONObject();
            try {
                json = new JSONObject(parameters);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //facebook.dialog(activity, "feed", JSONtoBundle(json), FBDialogListener );
            //            Bundle params = new Bundle();
            //             params.putString("name", "Facebook SDK for Android");
            //             params.putString("caption", "Build great social apps and get more installs.");
            //             params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
            //             params.putString("link", "https://developers.facebook.com/android");
            //             params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
            Bundle params = JSONtoBundle(json);

            params.putString("frictionless", useFrictionless);

            WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(activity, session, params))
                    .setOnCompleteListener(new OnCompleteListener() {

                        @Override
                        public void onComplete(Bundle values, FacebookException error) {
                            if (error == null) {
                                // When the story is posted, echo the success
                                // and the post Id.
                                final String postId = values.getString("post_id");
                                if (postId != null) {
                                    //                                 Toast.makeText(activity,
                                    //                                     "Posted story, id: "+postId,
                                    //                                     Toast.LENGTH_SHORT).show();
                                    JSONObject jsonData = BundleToJSON(values);
                                    String extra = "";

                                    try {
                                        String request = jsonData.getString("request");
                                        extra += "e.request=" + request + ";";
                                    } catch (JSONException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }

                                    int index = 0;
                                    if (jsonData.has("to[" + index + "]")) {
                                        extra += "e.to=[";
                                        while (jsonData.has("to[" + index + "]")) {
                                            try {
                                                extra += jsonData.getString("to[" + index + "]") + ",";
                                            } catch (JSONException e) {
                                            }
                                            index++;
                                        }
                                        extra += "];";
                                    }

                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=true;e.error='';e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}%sdocument.dispatchEvent(e);",
                                            jsonData.toString(), extra);
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                } else {
                                    // User clicked the Cancel button
                                    //                                 Toast.makeText(activity.getApplicationContext(), 
                                    //                                     "Publish cancelled", 
                                    //                                     Toast.LENGTH_SHORT).show();
                                    String js = String.format(
                                            "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                    webView.loadUrl(js);
                                    resetFBStatus();
                                }
                            } else if (error instanceof FacebookOperationCanceledException) {
                                // User clicked the "x" button
                                //                             Toast.makeText(activity.getApplicationContext(), 
                                //                                 "Publish cancelled", 
                                //                                 Toast.LENGTH_SHORT).show();
                                String js = String.format(
                                        "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
                                webView.loadUrl(js);
                                resetFBStatus();
                            } else {
                                // Generic, ex: network error
                                //                             Toast.makeText(activity.getApplicationContext(), 
                                //                                 "Error posting story", 
                                //                                 Toast.LENGTH_SHORT).show();
                                String js = String.format(
                                        "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);",
                                        error.toString());
                                webView.loadUrl(js);
                                resetFBStatus();
                            }
                        }

                    }).build();
            feedDialog.show();
        }
    });

}

From source file:ch.icclab.cyclops.resource.impl.ExternalAppResource.java

/**
 * Receives the JSON data sent by an external application
 *
 * Pseudo Code/*from w w w  .  j  av a 2  s  .  c  om*/
 * 1. Receive the data
 * 2. Extract the JSON array
 * 3. Send the JSON array to saveData() for further processing
 *
 * @param entity
 * @return Representation A JSON response is returned
 */
@Post("json:json")
public Representation receiveRequest(JsonRepresentation entity) {

    JSONArray jsonArr = null;
    boolean output = true;

    LocalDateTime currentDateTime = new LocalDateTime();
    Response response = new Response();
    Representation jsonResponse = new JsonRepresentation(response);
    ResponseUtil util = new ResponseUtil();

    try {
        jsonArr = entity.getJsonArray();
        output = saveData(jsonArr);
    } catch (JSONException e) {
        output = false;
        e.printStackTrace();
    }
    response.setTimestamp(currentDateTime.toDateTime().toString());
    if (output) {
        response.setStatus("Success");
        response.setMessage("Data saved into the DB");
    } else {
        response.setStatus("Failure");
        response.setMessage("Data could not be saved into the DB");
    }
    jsonResponse = util.toJson(response);
    return jsonResponse;
}

From source file:ch.icclab.cyclops.resource.impl.ExternalAppResource.java

/**
 * Receives the JSON array, transforms it and send it to the db resource to persist it into InfluxDB
 *
 * Pseudo Code/*from   www .  j av a2s.  c  o m*/
 * 1. Iterate through the JSONArray to get the JSON obj
 * 2. Iterate through the JSON Obj to get the usage details
 * 3. Build the TSDB POJO
 * 4. Pass this POJO obj to the TSDB resource for persisting it into the DB
 *
 * @param jsonArr An array containing the usage data as part of JSON Objects
 * @return String
 */
public boolean saveData(JSONArray jsonArr) {

    JSONObject jsonObj, metadata, usageData;
    String metername = null;
    String source;
    TSDBResource dbResource = new TSDBResource();
    JSONArray dataArr;
    ArrayList<Object> objArrNode;
    ArrayList<ArrayList<Object>> objArr = new ArrayList<ArrayList<Object>>();
    TSDBData dbData = new TSDBData();
    ArrayList<String> columnNameArr = new ArrayList<String>();
    columnNameArr.add("timestamp");
    columnNameArr.add("userid");
    columnNameArr.add("source");
    columnNameArr.add("usage");

    try {
        for (int i = 0; i < jsonArr.length(); i++) {
            jsonObj = (JSONObject) jsonArr.get(i);
            metadata = (JSONObject) jsonObj.get("metadata");
            source = (String) metadata.get("source");
            dataArr = (JSONArray) jsonObj.get("usage");

            for (int j = 0; j < dataArr.length(); j++) {
                objArrNode = new ArrayList<Object>();
                usageData = (JSONObject) dataArr.get(j);
                metername = (String) usageData.get("metername");
                objArrNode.add(usageData.get("timestamp"));
                objArrNode.add(usageData.get("userid"));
                objArrNode.add(source);
                objArrNode.add(usageData.get("usage"));
                objArr.add(objArrNode);
            }
            dbData.setName(metername);
            dbData.setColumns(columnNameArr);
            dbData.setPoints(objArr);

            dbResource.saveExtData(dbData);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.prx.prp.utility.ParsedJSONObject.java

public ParsedJSONObject(JSONObject object) {
    int index;/*from  w  ww . j  a  va 2  s. c  om*/
    values = new String[names.length];
    for (index = 0; index < this.names.length; index++) {
        try {
            values[index] = object.getString(names[index]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    checkForDelete(object);
}

From source file:org.prx.prp.utility.ParsedJSONObject.java

private void checkForDelete(JSONObject object) {
    try {// www . ja  va2  s .c om
        if (object.getString("deleted_at") != "null")
            toBeDeleted = true;
        else
            toBeDeleted = false;
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:org.prx.prp.utility.ParsedJSONObject.java

private void storeId(JSONObject object) {
    try {//w w w .j  ava  2s .c o m
        this.id = object.getInt("id");

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

From source file:com.andybotting.tramhunter.objects.FavouriteList.java

/**
 * Get the favourite items/*from  w ww.ja  va 2  s .  c  om*/
 * @return 
 */
public ArrayList<Favourite> getFavouriteItems() {

    ArrayList<Favourite> favourites = new ArrayList<Favourite>();
    JSONArray favouriteJSONArray = null;
    TramHunterDB db = new TramHunterDB();

    // Fetch JSON favourite stops string from preferences
    String favouriteString = mPreferenceHelper.getStarredStopsString();
    if (LOGV)
        Log.i(TAG, "Parsing favourite string: " + favouriteString);

    // Check to see if we even have any favourites
    if (favouriteString.length() > 1) {

        // Convert any old favourites - if not a JSON Array
        if (!favouriteString.contains("["))
            favouriteString = convertOldFavourites(favouriteString);

        try {
            favouriteJSONArray = new JSONArray(favouriteString);

            for (int i = 0; i < favouriteJSONArray.length(); i++) {

                JSONObject favouriteJSONObject = favouriteJSONArray.getJSONObject(i);

                int tramTrackerID = favouriteJSONObject.optInt("stop");
                int routeID = favouriteJSONObject.optInt("route", -1);
                String name = favouriteJSONObject.optString("name", null);

                Stop stop = db.getStop(tramTrackerID);
                Route route = null;

                if (routeID != -1)
                    route = db.getRoute(routeID);

                favourites.add(new Favourite(stop, route, name));
            }

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

    }
    db.close();
    return favourites;
}

From source file:org.rapidandroid.activity.FormCreator.java

private void saveState() {
    // TODO Auto-generated method stub
    // this.d//from w ww  . j a v  a 2 s.  co  m
    JSONObject savedstate = new JSONObject();
    EditText etxFormName = (EditText) findViewById(R.id.etx_formname);
    EditText etxFormPrefix = (EditText) findViewById(R.id.etx_formprefix);
    EditText etxDescription = (EditText) findViewById(R.id.etx_description);
    //      ListView lsv = (ListView) findViewById(R.id.lsv_createfields);

    try {
        savedstate.put(STATE_FORMNAME, etxFormName.getText().toString());
        savedstate.put(STATE_PREFIX, etxFormPrefix.getText().toString());
        savedstate.put(STATE_DESC, etxDescription.getText().toString());
        savedstate.put(STATE_PARSER, mChosenParser.getName());

        if (mCurrentFields != null) {
            int numFields = this.mCurrentFields.size();
            for (int i = 0; i < numFields; i++) {
                Field f = mCurrentFields.get(i);

                JSONObject fieldobj = new JSONObject();

                fieldobj.put(AddField.ResultConstants.RESULT_KEY_FIELDNAME, f.getName());
                fieldobj.put(AddField.ResultConstants.RESULT_KEY_DESCRIPTION, f.getDescription());
                fieldobj.put(AddField.ResultConstants.RESULT_KEY_FIELDTYPE_ID,
                        ((SimpleFieldType) f.getFieldType()).getId());
                savedstate.put("Field" + i, fieldobj);
            }
        }

        getIntent().putExtra("current_form", savedstate.toString());

    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        Log.d("FormCreator", e1.getMessage());
    }
}

From source file:com.keylesspalace.tusky.util.NotificationMaker.java

public static void make(final Context context, final int notifyId, Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences notificationPreferences = context.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);

    if (!filterNotification(preferences, body)) {
        return;/*from  w w  w .  j  a v a  2s  .  co  m*/
    }

    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;

    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }

    boolean alreadyContains = false;

    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.getDisplayName())) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (!alreadyContains) {
        currentNotifications.put(body.account.getDisplayName());
    }

    notificationPreferences.edit().putString("current", currentNotifications.toString()).commit();

    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent deleteIntent = new Intent(context, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent)
            .setDeleteIntent(deletePendingIntent).setDefaults(0); // So it doesn't ring twice, notify only in Target callback

    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(context, body))
                .setContentText(truncateWithEllipses(bodyForType(body), 40));

        Target mTarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                builder.setLargeIcon(bitmap);

                setupPreferences(preferences, builder);

                ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE)))
                        .notify(notifyId, builder.build());
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        };

        Picasso.with(context).load(body.account.avatar).placeholder(R.drawable.avatar_default)
                .transform(new RoundedTransformation(7, 0)).into(mTarget);
    } else {
        setupPreferences(preferences, builder);
        try {
            builder.setContentTitle(String.format(context.getString(R.string.notification_title_summary),
                    currentNotifications.length()))
                    .setContentText(truncateWithEllipses(joinNames(context, currentNotifications), 40));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }

    ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE))).notify(notifyId,
            builder.build());
}