Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:org.apache.cordova.filetransfer.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 * @param callbackContext    callback id for optional progress reports
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *//*from  w  w  w.jav  a2 s  .  c om*/
private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    // Setup the options
    final String fileKey = getArgument(args, 2, "file");
    final String fileName = getArgument(args, 3, "image.jpg");
    final String mimeType = getArgument(args, 4, "image/jpeg");
    final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
    final boolean trustEveryone = args.optBoolean(6);
    // Always use chunked mode unless set to false as per API
    final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
    // Look for headers on the params map for backwards compatibility with older Cordova versions.
    final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers")
            : args.optJSONObject(8);
    final String objectId = args.getString(9);
    final String httpMethod = getArgument(args, 10, "POST");

    final CordovaResourceApi resourceApi = webView.getResourceApi();

    Log.d(LOG_TAG, "fileKey: " + fileKey);
    Log.d(LOG_TAG, "fileName: " + fileName);
    Log.d(LOG_TAG, "mimeType: " + mimeType);
    Log.d(LOG_TAG, "params: " + params);
    Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
    Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
    Log.d(LOG_TAG, "headers: " + headers);
    Log.d(LOG_TAG, "objectId: " + objectId);
    Log.d(LOG_TAG, "httpMethod: " + httpMethod);

    final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
    // Accept a path or a URI for the source.
    Uri tmpSrc = Uri.parse(source);
    final Uri sourceUri = resourceApi
            .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));

    int uriType = CordovaResourceApi.getUriType(targetUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
        Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection conn = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            int totalBytes = 0;
            int fixedLength = -1;
            try {
                // Create return object
                FileUploadResult result = new FileUploadResult();
                FileProgressResult progress = new FileProgressResult();

                //------------------ CLIENT REQUEST
                // Open a HTTP connection to the URL based on protocol
                conn = resourceApi.createHttpConnection(targetUri);
                if (useHttps && trustEveryone) {
                    // Setup the HTTPS connection class to trust everyone
                    HttpsURLConnection https = (HttpsURLConnection) conn;
                    oldSocketFactory = trustAllHosts(https);
                    // Save the current hostnameVerifier
                    oldHostnameVerifier = https.getHostnameVerifier();
                    // Setup the connection not to verify hostnames
                    https.setHostnameVerifier(DO_NOT_VERIFY);
                }

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod(httpMethod);

                // if we specified a Content-Type header, don't do multipart form upload
                boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type");
                if (multipartFormUpload) {
                    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
                }

                // Set the cookies on the response
                String cookie = getCookies(target);

                if (cookie != null) {
                    conn.setRequestProperty("Cookie", cookie);
                }

                // Handle the other headers
                if (headers != null) {
                    addHeadersToRequest(conn, headers);
                }

                /*
                * Store the non-file portions of the multipart data as a string, so that we can add it
                * to the contentSize, since it is part of the body of the HTTP request.
                */
                StringBuilder beforeData = new StringBuilder();
                try {
                    for (Iterator<?> iter = params.keys(); iter.hasNext();) {
                        Object key = iter.next();
                        if (!String.valueOf(key).equals("headers")) {
                            beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
                            beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString())
                                    .append('"');
                            beforeData.append(LINE_END).append(LINE_END);
                            beforeData.append(params.getString(key.toString()));
                            beforeData.append(LINE_END);
                        }
                    }
                } catch (JSONException e) {
                    Log.e(LOG_TAG, e.getMessage(), e);
                }

                beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
                beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";");
                beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);
                beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END);
                byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");
                byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END)
                        .getBytes("UTF-8");

                // Get a input stream of the file on the phone
                OpenForReadResult readResult = resourceApi.openForRead(sourceUri);

                int stringLength = beforeDataBytes.length + tailParamsBytes.length;
                if (readResult.length >= 0) {
                    fixedLength = (int) readResult.length;
                    if (multipartFormUpload)
                        fixedLength += stringLength;
                    progress.setLengthComputable(true);
                    progress.setTotal(fixedLength);
                }
                Log.d(LOG_TAG, "Content Length: " + fixedLength);
                // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
                // http://code.google.com/p/android/issues/detail?id=3164
                // It also causes OOM if HTTPS is used, even on newer devices.
                boolean useChunkedMode = chunkedMode
                        && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
                useChunkedMode = useChunkedMode || (fixedLength == -1);

                if (useChunkedMode) {
                    conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
                    // Although setChunkedStreamingMode sets this header, setting it explicitly here works
                    // around an OutOfMemoryException when using https.
                    conn.setRequestProperty("Transfer-Encoding", "chunked");
                } else {
                    conn.setFixedLengthStreamingMode(fixedLength);
                }

                conn.connect();

                OutputStream sendStream = null;
                try {
                    sendStream = conn.getOutputStream();
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.connection = conn;
                    }

                    if (multipartFormUpload) {
                        //We don't want to change encoding, we just want this to write for all Unicode.
                        sendStream.write(beforeDataBytes);
                        totalBytes += beforeDataBytes.length;
                    }

                    // create a buffer of maximum size
                    int bytesAvailable = readResult.inputStream.available();
                    int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                    byte[] buffer = new byte[bufferSize];

                    // read file and write it into form...
                    int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                    long prevBytesRead = 0;
                    while (bytesRead > 0) {
                        result.setBytesSent(totalBytes);
                        sendStream.write(buffer, 0, bytesRead);
                        totalBytes += bytesRead;
                        if (totalBytes > prevBytesRead + 102400) {
                            prevBytesRead = totalBytes;
                            Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
                        }
                        bytesAvailable = readResult.inputStream.available();
                        bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                        bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                        // Send a progress event.
                        progress.setLoaded(totalBytes);
                        PluginResult progressResult = new PluginResult(PluginResult.Status.OK,
                                progress.toJSONObject());
                        progressResult.setKeepCallback(true);
                        context.sendPluginResult(progressResult);
                    }

                    if (multipartFormUpload) {
                        // send multipart form data necessary after file data...
                        sendStream.write(tailParamsBytes);
                        totalBytes += tailParamsBytes.length;
                    }
                    sendStream.flush();
                } finally {
                    safeClose(readResult.inputStream);
                    safeClose(sendStream);
                }
                synchronized (context) {
                    context.connection = null;
                }
                Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);

                //------------------ read the SERVER RESPONSE
                String responseString;
                int responseCode = conn.getResponseCode();
                Log.d(LOG_TAG, "response code: " + responseCode);
                Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
                TrackingInputStream inStream = null;
                try {
                    inStream = getInputStream(conn);
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.connection = conn;
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream(
                            Math.max(1024, conn.getContentLength()));
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    // write bytes to file
                    while ((bytesRead = inStream.read(buffer)) > 0) {
                        out.write(buffer, 0, bytesRead);
                    }
                    responseString = out.toString("UTF-8");
                } finally {
                    synchronized (context) {
                        context.connection = null;
                    }
                    safeClose(inStream);
                }

                Log.d(LOG_TAG, "got response from server");
                Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));

                // send request and retrieve response
                result.setResponseCode(responseCode);
                result.setResponse(responseString);

                context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn, e);
                Log.e(LOG_TAG, error.toString(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, e);
                Log.e(LOG_TAG, error.toString(), e);
                Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            } catch (Throwable t) {
                // Shouldn't happen, but will
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, t);
                Log.e(LOG_TAG, error.toString(), t);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } finally {
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (conn != null) {
                    // Revert back to the proper verifier and socket factories
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) conn;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }
            }
        }
    });
}

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

@Test
public void testCheckoutEmptyPaths() throws Exception {
    // clone a repo
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    clone(clonePath);/*from  w  ww  . j a v a 2 s . c  o m*/

    // get project metadata
    WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());

    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);
    String gitCloneUri = gitSection.getString(GitConstants.KEY_CLONE);

    request = getCheckoutRequest(gitCloneUri, new String[] {});
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode());
}

From source file:com.ota.updates.json.VersionJSONParser.java

/**
 * Parse the Versions array within the selected JSON string
 *///from ww w .j a v a2s .  co  m
public boolean parse() {
    try {
        JSONObject jObj = new JSONObject(mJSONString);

        JSONObject romObj = jObj.getJSONObject(NAME_ROM);

        JSONArray versionsArray = romObj.getJSONArray(NAME_VERSIONS);

        VersionSQLiteHelper helper = new VersionSQLiteHelper(mContext);

        for (int i = 0; i < versionsArray.length(); i++) {
            JSONObject arrayObj = versionsArray.getJSONObject(i);

            JSONObject versionObj = arrayObj.getJSONObject(NAME_VERSION);

            VersionItem versionItem = new VersionItem();
            versionItem.setId(versionObj.getInt(NAME_ID));
            versionItem.setDownloads(versionObj.getInt(NAME_DOWNLOADS));
            versionItem.setFullName(versionObj.getString(NAME_FULL_NAME));
            versionItem.setSlug(versionObj.getString(NAME_SLUG));
            versionItem.setAndroidVersion(versionObj.getString(NAME_ANDROID_VERSION));
            versionItem.setChangelog(versionObj.getString(NAME_CHANGELOG));
            versionItem.setCreatedAt(versionObj.getString(NAME_CREATED_AT));
            versionItem.setPublishedAt(versionObj.getString(NAME_PUBLISHED_AT));
            versionItem.setVersionNumber(versionObj.getInt(NAME_VERSION_NUMBER));

            JSONObject deltaObj = versionObj.optJSONObject(NAME_DELTA_UPLOAD);
            if (deltaObj != null) {
                versionItem.setDeltaUploadId(deltaObj.getInt(NAME_ID));
                new UploadJSONParser(mContext, deltaObj.toString()).parse();
            } else {
                versionItem.setDeltaUploadId(-1);
            }

            JSONObject fullObj = versionObj.getJSONObject(NAME_FULL_UPLOAD);
            versionItem.setFullUploadId(fullObj.getInt(NAME_ID));
            new UploadJSONParser(mContext, fullObj.toString()).parse();

            helper.addVersion(versionItem);
        }
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
        return false;
    }
    return true;
}

From source file:com.purplefrog.glitchclocka.LearningReadout.java

public void handleJSONResponse(JSONObject json) {
    JSONObject learning_ = json.optJSONObject("learning");

    if (learning_ == null) {
        learningState = new LearningState("nothing", System.currentTimeMillis() / 1000, 0, "",
                "you're not learnin' nuthin.");
        updateReadoutFull();// ww  w  . j  av  a 2s  . c  o  m
        return;
    }

    String skillId = learning_.keys().next().toString();
    JSONObject learning = learning_.optJSONObject(skillId);

    String name = learning.optString("name");
    long timeComplete = learning.optLong("time_complete");
    int totalTime = learning.optInt("total_time");
    String skillIconURL = learning.optString("icon_100");
    String description = learning.optString("description");

    learningState = new LearningState(name, timeComplete, totalTime, skillIconURL, description);
    updateReadoutFull();

    final String partial = name + " " + timeComplete + " " + totalTime + " " + skillIconURL + " \n"
            + description;

    debugText.setText(partial + "\n\n" + json);
}

From source file:com.melniqw.instagramsdk.Comment.java

public static Comment fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Comment comment = new Comment();
    comment.id = o.optString("id");
    comment.createdTime = o.optString("created_time");
    comment.text = o.optString("name");
    comment.user = User.fromJSON(o.optJSONObject("from"));
    return comment;
}

From source file:com.soomla.levelup.LevelUp.java

public static HashMap<String, JSONObject> getGates(JSONObject model) {
    HashMap<String, JSONObject> resultHash = new HashMap<String, JSONObject>();

    HashMap<String, JSONObject> worldJSONs = getWorlds(model);

    for (JSONObject worldJSON : worldJSONs.values()) {
        JSONObject gateJSON = worldJSON.optJSONObject("gate");

        if (gateJSON != null) {
            String objectId = gateJSON.optString("itemId");
            if (!TextUtils.isEmpty(objectId)) {
                resultHash.put(objectId, gateJSON);
            }/*from w  ww.  j  a v  a  2 s . c o m*/
        }
    }

    HashMap<String, JSONObject> missionJSONs = getMissions(model);
    for (JSONObject missionJSON : missionJSONs.values()) {
        JSONObject gateJSON = missionJSON.optJSONObject("gate");

        if (gateJSON != null) {
            String objectId = gateJSON.optString("itemId");
            if (!TextUtils.isEmpty(objectId)) {
                resultHash.put(objectId, gateJSON);
            }
        }
    }

    findInternalLists(resultHash, new String[] { "GatesListAND", "GatesListOR" }, "gates");

    return resultHash;
}

From source file:com.melniqw.instagramsdk.Api.java

/**
 * https://instagram.com/developer/endpoints/users/#get_users
 *///  ww  w .j  a v a2  s  .  c om
public static UserInfo getUserInfo(String userId, String accessToken) throws IOException, JSONException {
    Params params = new Params("/users/" + userId + "/");
    params.put("access_token", accessToken);
    JSONObject rootJSON = Network.sendRequest(Api.API_BASE_URL, params, Network.Request.GET);
    JSONObject userInfoJSON = rootJSON.optJSONObject("data");
    return UserInfo.fromJSON(userInfoJSON);
}

From source file:com.vk.sdkweb.api.model.VKApiUserFull.java

public VKApiUserFull parse(JSONObject user) {
    super.parse(user);

    // general/*from   w w w .java 2 s . com*/
    last_seen = parseLong(user.optJSONObject(LAST_SEEN), "time");
    bdate = user.optString(BDATE);

    JSONObject city = user.optJSONObject(CITY);
    if (city != null) {
        this.city = new VKApiCity().parse(city);
    }
    JSONObject country = user.optJSONObject(COUNTRY);
    if (country != null) {
        this.country = new VKApiCountry().parse(country);
    }

    // education
    universities = new VKList<VKApiUniversity>(user.optJSONArray(UNIVERSITIES), VKApiUniversity.class);
    schools = new VKList<VKApiSchool>(user.optJSONArray(SCHOOLS), VKApiSchool.class);

    // status
    activity = user.optString(ACTIVITY);

    JSONObject status_audio = user.optJSONObject("status_audio");
    if (status_audio != null)
        this.status_audio = new VKApiAudio().parse(status_audio);

    // personal views
    JSONObject personal = user.optJSONObject(PERSONAL);
    if (personal != null) {
        smoking = personal.optInt("smoking");
        alcohol = personal.optInt("alcohol");
        political = personal.optInt("political");
        life_main = personal.optInt("life_main");
        people_main = personal.optInt("people_main");
        inspired_by = personal.optString("inspired_by");
        religion = personal.optString("religion");
        if (personal.has("langs")) {
            JSONArray langs = personal.optJSONArray("langs");
            if (langs != null) {
                this.langs = new String[langs.length()];
                for (int i = 0; i < langs.length(); i++) {
                    this.langs[i] = langs.optString(i);
                }
            }
        }
    }

    // contacts
    facebook = user.optString("facebook");
    facebook_name = user.optString("facebook_name");
    livejournal = user.optString("livejournal");
    site = user.optString(SITE);
    screen_name = user.optString("screen_name", "id" + id);
    skype = user.optString("skype");
    mobile_phone = user.optString("mobile_phone");
    home_phone = user.optString("home_phone");
    twitter = user.optString("twitter");
    instagram = user.optString("instagram");

    // personal info
    about = user.optString(ABOUT);
    activities = user.optString(ACTIVITIES);
    books = user.optString(BOOKS);
    games = user.optString(GAMES);
    interests = user.optString(INTERESTS);
    movies = user.optString(MOVIES);
    quotes = user.optString(QUOTES);
    tv = user.optString(TV);

    // settings
    nickname = user.optString("nickname", null);
    can_post = parseBoolean(user, CAN_POST);
    can_see_all_posts = parseBoolean(user, CAN_SEE_ALL_POSTS);
    blacklisted_by_me = parseBoolean(user, BLACKLISTED_BY_ME);
    can_write_private_message = parseBoolean(user, CAN_WRITE_PRIVATE_MESSAGE);
    wall_comments = parseBoolean(user, WALL_DEFAULT);
    String deactivated = user.optString("deactivated");
    is_deleted = "deleted".equals(deactivated);
    is_banned = "banned".equals(deactivated);
    wall_default_owner = "owner".equals(user.optString(WALL_DEFAULT));
    verified = parseBoolean(user, VERIFIED);

    // other
    sex = user.optInt(SEX);
    JSONObject counters = user.optJSONObject(COUNTERS);
    if (counters != null)
        this.counters = new Counters(counters);

    relation = user.optInt(RELATION);

    if (user.has(RELATIVES)) {
        if (relatives == null) {
            relatives = new VKList<Relative>();
        }
        relatives.fill(user.optJSONArray(RELATIVES), Relative.class);
    }
    return this;
}

From source file:com.melniqw.instagramsdk.UserInPhoto.java

public static UserInPhoto fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    UserInPhoto userInPhoto = new UserInPhoto();
    JSONObject positionJSON = o.optJSONObject("position");
    userInPhoto.position.x = positionJSON.optDouble("x");
    userInPhoto.position.y = positionJSON.optDouble("y");
    JSONObject userJSON = o.optJSONObject("user");
    userInPhoto.user = User.fromJSON(userJSON);
    return userInPhoto;
}

From source file:org.catnut.fragment.TweetFragment.java

private void loadTweet() {
    // load tweet from local...
    String query = CatnutUtils.buildQuery(
            new String[] { Status.uid, Status.columnText, Status.bmiddle_pic, Status.original_pic,
                    Status.comments_count, Status.reposts_count, Status.attitudes_count, Status.source,
                    Status.favorited, Status.retweeted_status, Status.pic_urls, "s." + Status.created_at,
                    User.screen_name, User.avatar_large, User.remark, User.verified },
            "s._id=" + mId, Status.TABLE + " as s", "inner join " + User.TABLE + " as u on s.uid=u._id", null,
            null);//  w  w w.  jav a2 s.  c o  m
    new AsyncQueryHandler(getActivity().getContentResolver()) {
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            if (cursor.moveToNext()) {
                Picasso.with(getActivity()).load(cursor.getString(cursor.getColumnIndex(User.avatar_large)))
                        .placeholder(R.drawable.error).error(R.drawable.error).into(mAvatar);
                final long uid = cursor.getLong(cursor.getColumnIndex(Status.uid));
                final String screenName = cursor.getString(cursor.getColumnIndex(User.screen_name));
                mAvatar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), ProfileActivity.class);
                        intent.putExtra(Constants.ID, uid);
                        intent.putExtra(User.screen_name, screenName);
                        startActivity(intent);
                    }
                });
                String remark = cursor.getString(cursor.getColumnIndex(User.remark));
                mRemark.setText(TextUtils.isEmpty(remark) ? screenName : remark);
                mScreenName.setText(getString(R.string.mention_text, screenName));
                mPlainText = cursor.getString(cursor.getColumnIndex(Status.columnText));
                mText.setText(mPlainText);
                CatnutUtils.vividTweet(mText, mImageSpan);
                CatnutUtils.setTypeface(mText, mTypeface);
                mText.setLineSpacing(0, mLineSpacing);
                int replyCount = cursor.getInt(cursor.getColumnIndex(Status.comments_count));
                mReplayCount.setText(CatnutUtils.approximate(replyCount));
                int retweetCount = cursor.getInt(cursor.getColumnIndex(Status.reposts_count));
                mReteetCount.setText(CatnutUtils.approximate(retweetCount));
                int favoriteCount = cursor.getInt(cursor.getColumnIndex(Status.attitudes_count));
                mFavoriteCount.setText(CatnutUtils.approximate(favoriteCount));
                String source = cursor.getString(cursor.getColumnIndex(Status.source));
                mSource.setText(Html.fromHtml(source).toString());
                mCreateAt.setText(DateUtils.getRelativeTimeSpanString(
                        DateTime.getTimeMills(cursor.getString(cursor.getColumnIndex(Status.created_at)))));
                if (CatnutUtils.getBoolean(cursor, User.verified)) {
                    mTweetLayout.findViewById(R.id.verified).setVisibility(View.VISIBLE);
                }
                String thumb = cursor.getString(cursor.getColumnIndex(Status.bmiddle_pic));
                String url = cursor.getString(cursor.getColumnIndex(Status.original_pic));
                loadThumbs(thumb, url, mThumbs,
                        CatnutUtils.optPics(cursor.getString(cursor.getColumnIndex(Status.pic_urls))),
                        mPicsOverflow);
                // retweet
                final String jsonString = cursor.getString(cursor.getColumnIndex(Status.retweeted_status));
                if (!TextUtils.isEmpty(jsonString)) {
                    View retweet = mRetweetLayout.inflate();
                    try {
                        JSONObject json = new JSONObject(jsonString);
                        JSONObject user = json.optJSONObject(User.SINGLE);
                        String _remark = user.optString(User.remark);
                        if (TextUtils.isEmpty(_remark)) {
                            _remark = user.optString(User.screen_name);
                        }
                        CatnutUtils.setText(retweet, R.id.retweet_nick,
                                getString(R.string.mention_text, _remark));
                        long mills = DateTime.getTimeMills(json.optString(Status.created_at));
                        CatnutUtils.setText(retweet, R.id.retweet_create_at,
                                DateUtils.getRelativeTimeSpanString(mills));
                        TweetTextView retweetText = (TweetTextView) CatnutUtils.setText(retweet,
                                R.id.retweet_text, json.optString(Status.text));
                        CatnutUtils.vividTweet(retweetText, mImageSpan);
                        CatnutUtils.setTypeface(retweetText, mTypeface);
                        retweetText.setLineSpacing(0, mLineSpacing);
                        retweet.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(getActivity(), TweetActivity.class);
                                intent.putExtra(Constants.JSON, jsonString);
                                startActivity(intent);
                            }
                        });
                        retweet.findViewById(R.id.verified)
                                .setVisibility(user.optBoolean(User.verified) ? View.VISIBLE : View.GONE);
                        if (json.has(Status.thumbnail_pic)) {
                            loadThumbs(json.optString(Status.bmiddle_pic), json.optString(Status.bmiddle_pic),
                                    (ImageView) retweet.findViewById(R.id.thumbs),
                                    json.optJSONArray(Status.pic_urls),
                                    retweet.findViewById(R.id.pics_overflow));
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "convert text to string error!", e);
                        retweet.setVisibility(View.GONE);
                    }
                }
                // shareAndFavorite&favorite
                shareAndFavorite(CatnutUtils.getBoolean(cursor, Status.favorited), mPlainText);
            }
            cursor.close();
        }
    }.startQuery(0, null, CatnutProvider.parse(Status.MULTIPLE), null, query, null, null);
}