Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

In this page you can find the example usage for org.json JSONObject toString.

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:com.cm.android.beercellar.ui.ImageDetailFragment.java

private void save() {
    try {/*from  w  ww .  jav a 2 s  .c om*/
        Note note = new Note();
        note.id = mRowId;
        note.beer = mBeer.getText().toString();
        note.rating = String.valueOf(mRatingBar.getRating());
        note.textExtract = mTextExtract.getText().toString();
        note.notes = mNotes.getText().toString();
        //default to Y
        note.share = "Y";
        note.picture = mRowId + Utils.PICTURES_EXTENSION;
        //note.share = mShare.isChecked() ? "Y" : "N";
        if (mIsNew) {
            mDbHelper.createNote(note);
            mIsNew = false;
        } else {
            mDbHelper.updateNote(note);
        }

        // Do the real work in an async task, because we need to use the network anyway
        new android.os.AsyncTask<Object, Void, Void>() {
            @Override
            protected Void doInBackground(Object... params) {
                NotesDbAdapter dbHelper = null;
                long rowId = (Long) params[0];
                try {
                    HttpTransport httpTransport = new NetHttpTransport();
                    HttpRequestFactory requestFactory = httpTransport.createRequestFactory(new MyInitializer());

                    JSONObject jsonObject = new JSONObject();

                    dbHelper = new NotesDbAdapter(getActivity());
                    dbHelper.open();
                    Note note = dbHelper.fetchNote(rowId);
                    jsonObject.put("rowId", note.id);
                    jsonObject.put("beer", note.beer);
                    jsonObject.put("rating", note.rating);
                    jsonObject.put("textExtract", note.textExtract);
                    jsonObject.put("notes", note.notes);
                    jsonObject.put("uri", note.uri);
                    jsonObject.put("timeCreatedMs", note.created);
                    jsonObject.put("timeCreatedTimeZoneOffsetMs", TimeZone.getDefault().getRawOffset());
                    jsonObject.put("timeUpdatedMs", note.updated);
                    jsonObject.put("timeUpdatedTimeZoneOffsetMs", TimeZone.getDefault().getRawOffset());

                    HttpResponse httpPostResponse = null;

                    try {
                        httpPostResponse = requestFactory.buildPutRequest(
                                new GenericUrl(Configuration.CONTENTS_URL),
                                new ByteArrayContent("application/json", jsonObject.toString().getBytes()))
                                .execute();

                        Log.i(sTag, "HTTP STATUS:: " + httpPostResponse.getStatusCode());

                    } finally {
                        httpPostResponse.disconnect();
                    }

                } catch (Throwable e) {
                    Log.e(sTag, "error: " + ((e.getMessage() != null) ? e.getMessage().replace(" ", "_") : ""),
                            e);
                } finally {
                    if (dbHelper != null)
                        dbHelper.close();

                }
                return null;
            }

        }.execute(mRowId);

    } catch (Throwable e) {
        Log.e(sTag, "error: " + ((e.getMessage() != null) ? e.getMessage().replace(" ", "_") : ""), e);
    }

}

From source file:com.surevine.alfresco.connector.SimpleAlfrescoHttpConnector.java

/**
 * POST a JSON object to a URL and parse out a JSON object from the response.
 * //w  ww . j a va  2s.c  o m
 * @param url
 *          URL to post to
 * @param json
 *          The JSON object to POST
 * @return The JSON response
 * @throws AlfrescoException
 *           On any HTTP error
 */
private void doHttpPost(final String url, final JSONObject json) throws AlfrescoException {
    StringEntity jsonEnt;

    try {
        jsonEnt = new StringEntity(json.toString());
    } catch (final UnsupportedEncodingException e) {
        throw new AlfrescoException("Failed on HTTP POST", e);
    }

    doHttpPost(url, jsonEnt);
}

From source file:com.deployd.Deployd.java

public static JSONObject put(JSONObject input, String uri)
        throws ClientProtocolException, IOException, JSONException {

    HttpPut post = new HttpPut(endpoint + uri);
    HttpClient client = new DefaultHttpClient();
    post.setEntity(new ByteArrayEntity(input.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(post);
    ByteArrayEntity e = (ByteArrayEntity) response.getEntity();
    InputStream is = e.getContent();
    String data = new Scanner(is).next();
    JSONObject result = new JSONObject(data);
    return result;
}

From source file:com.deployd.Deployd.java

public static JSONObject post(JSONObject input, String uri)
        throws ClientProtocolException, IOException, JSONException {

    HttpPost post = new HttpPost(endpoint + uri);
    HttpClient client = new DefaultHttpClient();
    post.setEntity(new ByteArrayEntity(input.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(post);
    ByteArrayEntity e = (ByteArrayEntity) response.getEntity();
    InputStream is = e.getContent();
    String data = new Scanner(is).next();
    JSONObject result = new JSONObject(data);
    return result;
}

From source file:com.mercandalli.android.apps.files.file.FileAddDialog.java

@SuppressWarnings("PMD.AvoidUsingHardCodedIP")
public FileAddDialog(@NonNull final Activity activity, final int id_file_parent,
        @Nullable final IListener listener, @Nullable final IListener dismissListener) {
    super(activity, R.style.DialogFullscreen);
    mActivity = activity;/* w  ww. j a  v a  2s . c o  m*/
    mDismissListener = dismissListener;
    mFileParentId = id_file_parent;
    mListener = listener;

    setContentView(R.layout.dialog_add_file);
    setCancelable(true);

    final View rootView = findViewById(R.id.dialog_add_file_root);
    rootView.startAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.dialog_add_file_open));
    rootView.setOnClickListener(this);

    findViewById(R.id.dialog_add_file_upload_file).setOnClickListener(this);
    findViewById(R.id.dialog_add_file_add_directory).setOnClickListener(this);

    findViewById(R.id.dialog_add_file_text_doc).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogUtils.prompt(mActivity, mActivity.getString(R.string.dialog_file_create_txt),
                    mActivity.getString(R.string.dialog_file_name_interrogation),
                    mActivity.getString(R.string.dialog_file_create),
                    new DialogUtils.OnDialogUtilsStringListener() {
                        @Override
                        public void onDialogUtilsStringCalledBack(String text) {
                            //TODO create a online txt with content
                            Toast.makeText(getContext(), getContext().getString(R.string.not_implemented),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }, mActivity.getString(android.R.string.cancel), null);
            FileAddDialog.this.dismiss();
        }
    });

    findViewById(R.id.dialog_add_file_scan).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // Ensure that there's a camera activity to handle the intent
            if (takePictureIntent.resolveActivity(mActivity.getPackageManager()) != null) {
                // Create the File where the photo should go
                ApplicationActivity.sPhotoFile = createImageFile();
                // Continue only if the File was successfully created
                if (ApplicationActivity.sPhotoFile != null) {
                    if (listener != null) {
                        ApplicationActivity.sPhotoFileListener = listener;
                    }
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(ApplicationActivity.sPhotoFile.getFile()));
                    mActivity.startActivityForResult(takePictureIntent, ApplicationActivity.REQUEST_TAKE_PHOTO);
                }
            }
            FileAddDialog.this.dismiss();
        }
    });

    findViewById(R.id.dialog_add_file_add_timer).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final Calendar currentTime = Calendar.getInstance();

            DialogDatePicker dialogDate = new DialogDatePicker(mActivity,
                    new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, final int year, final int monthOfYear,
                                final int dayOfMonth) {

                            Calendar currentTime = Calendar.getInstance();

                            DialogTimePicker dialogTime = new DialogTimePicker(mActivity,
                                    new TimePickerDialog.OnTimeSetListener() {
                                        @Override
                                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                            Log.d("TIme Picker", hourOfDay + ":" + minute);

                                            final SimpleDateFormat dateFormatGmt = new SimpleDateFormat(
                                                    "yyyy-MM-dd HH:mm:ss", Locale.US);
                                            dateFormatGmt.setTimeZone(TimeZone.getTimeZone("UTC"));
                                            final SimpleDateFormat dateFormatLocal = new SimpleDateFormat(
                                                    "yyyy-MM-dd HH:mm:ss", Locale.US);

                                            String nowAsISO = dateFormatGmt.format(new Date());

                                            final JSONObject json = new JSONObject();
                                            try {
                                                json.put("type", "timer");
                                                json.put("date_creation", nowAsISO);
                                                json.put("timer_date",
                                                        "" + dateFormatGmt.format(dateFormatLocal.parse(year
                                                                + "-" + (monthOfYear + 1) + "-" + dayOfMonth
                                                                + " " + hourOfDay + ":" + minute + ":00")));

                                                final SimpleDateFormat dateFormatGmtTZ = new SimpleDateFormat(
                                                        "yyyy-MM-dd'T'HH-mm'Z'", Locale.US);
                                                dateFormatGmtTZ.setTimeZone(TimeZone.getTimeZone("UTC"));
                                                nowAsISO = dateFormatGmtTZ.format(new Date());

                                                final List<StringPair> parameters = new ArrayList<>();
                                                parameters.add(new StringPair("content", json.toString()));
                                                parameters.add(new StringPair("name", "TIMER_" + nowAsISO));
                                                parameters.add(
                                                        new StringPair("id_file_parent", "" + id_file_parent));
                                                new TaskPost(mActivity,
                                                        Constants.URL_DOMAIN + Config.ROUTE_FILE,
                                                        new IPostExecuteListener() {
                                                            @Override
                                                            public void onPostExecute(JSONObject json,
                                                                    String body) {
                                                                if (listener != null) {
                                                                    listener.execute();
                                                                }
                                                            }
                                                        }, parameters).execute();
                                            } catch (JSONException | ParseException e) {
                                                Log.e(getClass().getName(), "Failed to convert Json", e);
                                            }

                                        }
                                    }, currentTime.get(Calendar.HOUR_OF_DAY), currentTime.get(Calendar.MINUTE),
                                    true);
                            dialogTime.show();

                        }
                    }, currentTime.get(Calendar.YEAR), currentTime.get(Calendar.MONTH),
                    currentTime.get(Calendar.DAY_OF_MONTH));
            dialogDate.show();

            FileAddDialog.this.dismiss();
        }
    });

    findViewById(R.id.dialog_add_file_article).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogCreateArticle dialogCreateArticle = new DialogCreateArticle(mActivity, listener);
            dialogCreateArticle.show();
            FileAddDialog.this.dismiss();
        }
    });

    FileAddDialog.this.show();
}

From source file:com.android.browser.GearsSettingsDialog.java

/**
 * Computes the difference between the original permissions and the
 * current ones. Returns a json-formatted string.
 * It is used by the Settings dialog./*from  www. j  a va  2s .co  m*/
 */
public String computeDiff(boolean modif) {
    String ret = null;
    try {
        JSONObject results = new JSONObject();
        JSONArray permissions = new JSONArray();

        for (int i = 0; modif && i < mOriginalPermissions.size(); i++) {
            OriginPermissions original = mOriginalPermissions.get(i);
            OriginPermissions current = mCurrentPermissions.get(i);
            JSONObject permission = new JSONObject();
            boolean modifications = false;

            for (int j = 0; j < mPermissions.size(); j++) {
                PermissionType type = mPermissions.get(j);

                if (current.getPermission(type) != original.getPermission(type)) {
                    JSONObject state = new JSONObject();
                    state.put("permissionState", current.getPermission(type));
                    permission.put(type.getName(), state);
                    modifications = true;
                }
            }

            if (modifications) {
                permission.put("name", current.getOrigin());
                permissions.put(permission);
            }
        }
        results.put("modifiedOrigins", permissions);
        ret = results.toString();
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception ", e);
    }
    return ret;
}

From source file:com.marpies.ane.facedetection.functions.DetectFacesFunction.java

private void dispatchResponse(JSONArray facesResult, int callbackId) {
    JSONObject response = new JSONObject();
    try {//from   ww  w  .ja  v a  2 s .  c o  m
        response.put("faces", facesResult.toString());
        response.put("callbackId", callbackId);
        AIR.dispatchEvent(FaceDetectionEvent.FACE_DETECTION_COMPLETE, response.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        AIR.log("Error creating JSON response");
        AIR.dispatchEvent(FaceDetectionEvent.FACE_DETECTION_ERROR,
                StringUtils.getEventErrorJSON(callbackId, "Error creating JSON response"));
    }
}

From source file:com.marpies.ane.facedetection.functions.DetectFacesFunction.java

private String getFaceJSON(Face face) {
    JSONObject json = new JSONObject();
    try {//from   w ww. java 2 s .  c  o m
        json.put("faceX", face.getPosition().x);
        json.put("faceY", face.getPosition().y);
        json.put("faceWidth", face.getWidth());
        json.put("faceHeight", face.getHeight());
        json.put("leftEyeOpenProbability", face.getIsLeftEyeOpenProbability());
        json.put("rightEyeOpenProbability", face.getIsRightEyeOpenProbability());
        json.put("isSmilingProbability", face.getIsSmilingProbability());
        List<Landmark> landmarks = face.getLandmarks();
        for (Landmark landmark : landmarks) {
            addLandmark(landmark, json);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
    return json.toString();
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitPullTest.java

static WebRequest getPostGitRemoteRequest(String location, boolean force)
        throws JSONException, UnsupportedEncodingException {
    String requestURI = toAbsoluteURI(location);
    JSONObject body = new JSONObject();
    body.put(GitConstants.KEY_PULL, Boolean.TRUE.toString());
    body.put(GitConstants.KEY_FORCE, force);
    WebRequest request = new PostMethodWebRequest(requestURI, IOUtilities.toInputStream(body.toString()),
            "UTF-8");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request);//w w w . ja  v a  2s.  co  m
    return request;
}

From source file:com.ifraag.facebookclient.FacebookClient.java

private Bundle prepBundleStoryWithLoc() {

    Bundle postParams = new Bundle();
    postParams.putString("message", " My Text Message ");

    /* According to SDK documentation: place object contains id and name of Page associated with this location,
    and a location field containing geographic information such as latitude, longitude, country */
    postParams.putString("place", placePageID);

    JSONObject coordinates = new JSONObject();
    try {/* w w  w  .ja v  a  2s.  c o  m*/
        coordinates.put("latitude", myLocation.getLatitude());
        coordinates.put("longitude", myLocation.getLongitude());
        Log.i(FB_CLIENT_TAG, "adding latitude and longitude");
    } catch (JSONException e) {
        e.printStackTrace();
        Log.w(FB_CLIENT_TAG, "Exception while adding latitude and longitude");
    }

    postParams.putString("coordinates", coordinates.toString());

    return postParams;
}