Example usage for org.json JSONObject optInt

List of usage examples for org.json JSONObject optInt

Introduction

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

Prototype

public int optInt(String key) 

Source Link

Document

Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number.

Usage

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

@Override
protected void refresh() {
    // ???/*  w  ww .  j  ava2 s .  co  m*/
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // refresh!
    final int size = getFetchSize();
    (new Thread(new Runnable() {
        @Override
        public void run() {
            // ??????(?-)???Orz...
            String query = CatnutUtils.buildQuery(new String[] { BaseColumns._ID }, mSelection, Status.TABLE,
                    null, BaseColumns._ID + " desc", size + ", 1" // limit x, y
            );
            Cursor cursor = getActivity().getContentResolver().query(CatnutProvider.parse(Status.MULTIPLE),
                    null, query, null, null);
            // the cursor never null?
            final long since_id;
            if (cursor.moveToNext()) {
                since_id = cursor.getLong(0);
            } else {
                since_id = 0;
            }
            cursor.close();
            final CatnutAPI api = TweetAPI.homeTimeline(since_id, 0, size, 0, 0, 0, 0);
            // refresh...
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mRequestQueue.add(new CatnutRequest(getActivity(), api,
                            new StatusProcessor.TimelineProcessor(Status.HOME, true),
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d(TAG, "refresh done...");
                                    mTotal = response.optInt(TOTAL_NUMBER);
                                    // ???
                                    JSONArray jsonArray = response.optJSONArray(Status.MULTIPLE);
                                    int newSize = jsonArray.length(); // ...
                                    Bundle args = new Bundle();
                                    args.putInt(TAG, newSize);
                                    getLoaderManager().restartLoader(0, args, HomeTimelineFragment.this);
                                }
                            }, errorListener)).setTag(TAG);
                }
            });
        }
    })).start();
}

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

private void loadFromCloud(long max_id) {
    mSwipeRefreshLayout.setRefreshing(true);
    CatnutAPI api = TweetAPI.homeTimeline(0, max_id, getFetchSize(), 0, 0, 0, 0);
    mRequestQueue.add(new CatnutRequest(getActivity(), api, new StatusProcessor.TimelineProcessor(true),
            new Response.Listener<JSONObject>() {
                @Override/*from   w  w w .ja  va  2  s  .  c o m*/
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "load more from cloud done...");
                    mTotal = response.optInt(TOTAL_NUMBER);
                    int newSize = response.optJSONArray(Status.MULTIPLE).length() + mAdapter.getCount();
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, HomeTimelineFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

From source file:com.mifos.mifosxdroid.dialogfragments.loanchargedialog.LoanChargeDialogFragment.java

@Override
public void showAllChargesV3(ResponseBody result) {

    /* Activity is null - Fragment has been detached; no need to do anything. */
    if (getActivity() == null)
        return;/*from w  w w  . ja  v  a2  s  .  c o  m*/

    Log.d(LOG_TAG, "");

    final List<Charges> charges = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> chargesNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("chargeOptions")) {
            JSONArray chargesTypes = obj.getJSONArray("chargeOptions");
            for (int i = 0; i < chargesTypes.length(); i++) {
                JSONObject chargesObject = chargesTypes.getJSONObject(i);
                Charges charge = new Charges();
                charge.setId(chargesObject.optInt("id"));
                charge.setName(chargesObject.optString("name"));
                charges.add(charge);
                chargesNames.add(chargesObject.optString("name"));
                chargeNameIdHashMap.put(charge.getName(), charge.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> chargesAdapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_spinner_item, chargesNames);
    chargesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp_charge_name.setAdapter(chargesAdapter);
    sp_charge_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Id = chargeNameIdHashMap.get(chargesNames.get(i));
            Log.d("chargesoptionss" + chargesNames.get(i), String.valueOf(Id));
            if (Id != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_charge), Toast.LENGTH_SHORT)
                        .show();

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

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

/**
 * Fills a School instance from JSONObject.
 *///from   w  w w  .  ja  va2s . c o  m
public VKApiSchool parse(JSONObject from) {
    id = from.optInt("id");
    country_id = from.optInt("country_id");
    city_id = from.optInt("city_id");
    name = from.optString("name");
    year_from = from.optInt("year_from");
    year_to = from.optInt("year_to");
    year_graduated = from.optInt("year_graduated");
    clazz = from.optString("class");
    speciality = from.optString("speciality");
    return this;
}

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

@Override
protected void refresh() {
    // ???//from   ww w  .  j  a v  a  2 s  .  c o  m
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // ??
    mCurrentPage = 0;
    mDeleteCount = 0;
    mTotal = 0;

    // go go go
    mRequestQueue.add(new CatnutRequest(getActivity(), FavoritesAPI.favorites(getFetchSize(), mCurrentPage),
            new StatusProcessor.FavoriteTweetsProcessor(), new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "refresh done...");
                    mDeleteCount += response.optInt(TAG);
                    mTotal = response.optInt(TOTAL_NUMBER);
                    // ???
                    JSONArray jsonArray = response.optJSONArray(Status.FAVORITES);
                    int newSize = jsonArray.length(); // ...
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, FavoriteFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

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

private void loadFromCloud() {
    mSwipeRefreshLayout.setRefreshing(true);
    mRequestQueue.add(new CatnutRequest(getActivity(), FavoritesAPI.favorites(getFetchSize(), mCurrentPage),
            new StatusProcessor.FavoriteTweetsProcessor(), new Response.Listener<JSONObject>() {
                @Override/*from   ww w . ja va  2s . c  om*/
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "load more from cloud done...");
                    mDeleteCount += response.optInt(TAG);
                    mTotal = response.optInt(TOTAL_NUMBER);
                    int newSize = response.optJSONArray(Status.FAVORITES).length() + mAdapter.getCount();
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, FavoriteFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

From source file:com.trellmor.berrytube.BerryTubeIOCallback.java

/**
 * @see io.socket.IOCallback#on(java.lang.String, io.socket.IOAcknowledge,
 *      java.lang.Object[])//from  w  ww  . j av a 2  s.  c  o  m
 */
public void on(String event, IOAcknowledge ack, Object... args) {
    if (event.compareTo("chatMsg") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject jsonMsg = (JSONObject) args[0];

            try {
                berryTube.getHandler()
                        .post(berryTube.new ChatMsgTask(new ChatMessage(jsonMsg.getJSONObject("msg"))));
            } catch (JSONException e) {
                Log.e(TAG, "chatMsg", e);
            }
        } else
            Log.w(TAG, "chatMsg message is not a JSONObject");
    } else if (event.compareTo("setNick") == 0) {
        if (args.length >= 1 && args[0] instanceof String) {
            berryTube.getHandler().post(berryTube.new SetNickTask((String) args[0]));
        } else
            Log.w(TAG, "setNick message is not a String");
    } else if (event.compareTo("loginError") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject error = (JSONObject) args[0];
            berryTube.getHandler()
                    .post(berryTube.new LoginErrorTask(error.optString("message", "Login failed")));
        }
    } else if (event.compareTo("userJoin") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject user = (JSONObject) args[0];
            try {
                berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                        BerryTube.UserJoinPartTask.ACTION_JOIN));
            } catch (JSONException e) {
                Log.e(TAG, "userJoin", e);
            }
        } else
            Log.w(TAG, "userJoin message is not a JSONObject");
    } else if (event.compareTo("newChatList") == 0) {
        berryTube.getHandler().post(berryTube.new UserResetTask());
        if (args.length >= 1 && args[0] instanceof JSONArray) {
            JSONArray users = (JSONArray) args[0];
            for (int i = 0; i < users.length(); i++) {
                JSONObject user = users.optJSONObject(i);
                if (user != null) {
                    try {
                        berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                                BerryTube.UserJoinPartTask.ACTION_JOIN));
                    } catch (JSONException e) {
                        Log.e(TAG, "newChatList", e);
                    }
                }
            }
        } else
            Log.w(TAG, "newChatList message is not a JSONArray");
    } else if (event.compareTo("userPart") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject user = (JSONObject) args[0];
            try {
                berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                        BerryTube.UserJoinPartTask.ACTION_PART));
            } catch (JSONException e) {
                Log.e(TAG, "userPart", e);
            }
        } else
            Log.w(TAG, "userPart message is not a JSONObject");
    } else if (event.compareTo("drinkCount") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject drinks = (JSONObject) args[0];
            berryTube.getHandler().post(berryTube.new DrinkCountTask(drinks.optInt("drinks")));
        }
    } else if (event.compareTo("kicked") == 0) {
        berryTube.getHandler().post(berryTube.new KickedTask());
    } else if (event.compareTo("newPoll") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject poll = (JSONObject) args[0];
            ChatMessage msg;

            // Send chat message for new poll
            try {
                msg = new ChatMessage(poll.getString("creator"), poll.getString("title"),
                        ChatMessage.EMOTE_POLL, 0, 0, false, 1);
                berryTube.getHandler().post(berryTube.new ChatMsgTask(msg));
            } catch (JSONException e) {
                Log.e(TAG, "newPoll", e);
            }

            // Create new poll
            try {
                berryTube.getHandler().post(berryTube.new NewPollTask(new Poll(poll)));
            } catch (JSONException e) {
                Log.e(TAG, "newPoll", e);
            }
        }
    } else if (event.compareTo("updatePoll") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject poll = (JSONObject) args[0];
            try {
                JSONArray votes = poll.getJSONArray("votes");
                int[] voteArray = new int[votes.length()];
                for (int i = 0; i < votes.length(); i++) {
                    voteArray[i] = votes.optInt(i, -1);
                }
                berryTube.getHandler().post(berryTube.new UpdatePollTask(voteArray));
            } catch (JSONException e) {
                Log.e(TAG, "updatePoll", e);
            }
        }
    } else if (event.compareTo("clearPoll") == 0) {
        berryTube.getHandler().post(berryTube.new ClearPollTask());
    } else if (event.compareTo("forceVideoChange") == 0 || event.compareTo("hbVideoDetail") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject videoMsg = (JSONObject) args[0];
            try {
                JSONObject video = videoMsg.getJSONObject("video");
                String name = URLDecoder.decode(video.getString("videotitle"), "UTF-8");
                String id = video.getString("videoid");
                String type = video.getString("videotype");
                berryTube.getHandler().post(berryTube.new NewVideoTask(name, id, type));
            } catch (JSONException | UnsupportedEncodingException e) {
                Log.w(TAG, e);
            }
        }
    }
}

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

public static Image fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Image image = new Image();
    JSONObject lowResolutionJSON = o.optJSONObject("low_resolution");
    image.lowResolution.url = lowResolutionJSON.optString("url");
    image.lowResolution.width = lowResolutionJSON.optInt("width");
    image.lowResolution.height = lowResolutionJSON.optInt("height");
    JSONObject standartResolutionJSON = o.optJSONObject("standard_resolution");
    image.standartResolution.url = standartResolutionJSON.optString("url");
    image.standartResolution.width = standartResolutionJSON.optInt("width");
    image.standartResolution.height = standartResolutionJSON.optInt("height");
    JSONObject thumbnailJSON = o.optJSONObject("thumbnail");
    image.thumbnail.url = thumbnailJSON.optString("url");
    image.thumbnail.width = thumbnailJSON.optInt("width");
    image.thumbnail.height = thumbnailJSON.optInt("height");
    return image;
}

From source file:com.entertailion.android.dial.MainActivity.java

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (requestCode == CODE_SWITCH_SERVER) {
        if (resultCode == RESULT_OK && data != null) {
            final DialServer dialServer = data.getParcelableExtra(ServerFinder.EXTRA_DIAL_SERVER);
            if (dialServer != null) {
                Toast.makeText(MainActivity.this, getString(R.string.finder_connected, dialServer.toString()),
                        Toast.LENGTH_LONG).show();
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            String device = "http://" + dialServer.getIpAddress().getHostAddress() + ":"
                                    + dialServer.getPort();
                            Log.d(LOG_TAG, "device=" + device);
                            Log.d(LOG_TAG, "apps url=" + dialServer.getAppsUrl());

                            // application instance url
                            String location = null;
                            String app = YOU_TUBE;

                            DefaultHttpClient defaultHttpClient = HttpRequestHelper.createHttpClient();
                            CustomRedirectHandler handler = new CustomRedirectHandler();
                            defaultHttpClient.setRedirectHandler(handler);
                            BasicHttpContext localContext = new BasicHttpContext();

                            // check if any app is running
                            HttpGet httpGet = new HttpGet(dialServer.getAppsUrl());
                            httpGet.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE);
                            httpGet.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
                            httpGet.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE);
                            httpGet.setHeader(HEADER_DNT, HEADER_DNT_VALUE);
                            httpGet.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE);
                            httpGet.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE);
                            HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
                            if (httpResponse != null) {
                                int responseCode = httpResponse.getStatusLine().getStatusCode();
                                Log.d(LOG_TAG,
                                        "get response code=" + httpResponse.getStatusLine().getStatusCode());
                                if (responseCode == 204) {
                                    // nothing is running
                                } else if (responseCode == 200) {
                                    // app is running

                                    // Need to get real URL after a redirect
                                    // http://stackoverflow.com/a/10286025/594751
                                    String lastUrl = dialServer.getAppsUrl();
                                    if (handler.lastRedirectedUri != null) {
                                        lastUrl = handler.lastRedirectedUri.toString();
                                        Log.d(LOG_TAG, "lastUrl=" + lastUrl);
                                    }/*  w w  w  .  j  ava2s.co m*/

                                    String response = EntityUtils.toString(httpResponse.getEntity());
                                    Log.d(LOG_TAG, "get response=" + response);
                                    parseXml(MainActivity.this, new StringReader(response));

                                    Header[] headers = httpResponse.getAllHeaders();
                                    for (int i = 0; i < headers.length; i++) {
                                        Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue());
                                    }

                                    // stop the app instance
                                    HttpDelete httpDelete = new HttpDelete(lastUrl);
                                    httpResponse = defaultHttpClient.execute(httpDelete);
                                    if (httpResponse != null) {
                                        Log.d(LOG_TAG, "delete response code="
                                                + httpResponse.getStatusLine().getStatusCode());
                                        response = EntityUtils.toString(httpResponse.getEntity());
                                        Log.d(LOG_TAG, "delete response=" + response);
                                    } else {
                                        Log.d(LOG_TAG, "no delete response");
                                    }
                                }

                            } else {
                                Log.i(LOG_TAG, "no get response");
                                return;
                            }

                            // Check if app is installed on device
                            int responseCode = getAppStatus(defaultHttpClient, dialServer.getAppsUrl() + app);
                            if (responseCode != 200) {
                                return;
                            }
                            parseXml(MainActivity.this, new StringReader(response));
                            Log.d(LOG_TAG, "state=" + state);

                            // start the app with POST
                            HttpPost httpPost = new HttpPost(dialServer.getAppsUrl() + app);
                            httpPost.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE);
                            httpPost.setHeader(HEADER_ORIGN, HEADER_ORIGIN_VALUE);
                            httpPost.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
                            httpPost.setHeader(HEADER_DNT, HEADER_DNT_VALUE);
                            httpPost.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE);
                            httpPost.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE);
                            httpPost.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE);
                            httpPost.setHeader(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_TEXT_VALUE);
                            // Set variable values as the body of the POST;
                            // v is the YouTube video id.
                            httpPost.setEntity(new StringEntity(
                                    "pairingCode=eac4ae42-8b54-4441-9be3-d8a9abb5c481&v=cKG5HDyTW8o&t=0")); // http://www.youtube.com/watch?v=cKG5HDyTW8o

                            httpResponse = defaultHttpClient.execute(httpPost, localContext);
                            if (httpResponse != null) {
                                Log.d(LOG_TAG,
                                        "post response code=" + httpResponse.getStatusLine().getStatusCode());
                                response = EntityUtils.toString(httpResponse.getEntity());
                                Log.d(LOG_TAG, "post response=" + response);
                                Header[] headers = httpResponse.getHeaders("LOCATION");
                                if (headers.length > 0) {
                                    location = headers[0].getValue();
                                    Log.d(LOG_TAG, "post response location=" + location);
                                }

                                headers = httpResponse.getAllHeaders();
                                for (int i = 0; i < headers.length; i++) {
                                    Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue());
                                }
                            } else {
                                Log.i(LOG_TAG, "no post response");
                                return;
                            }

                            // Keep trying to get the app status until the
                            // connection service URL is available
                            state = STATE_STOPPED;
                            do {
                                responseCode = getAppStatus(defaultHttpClient, dialServer.getAppsUrl() + app);
                                if (responseCode != 200) {
                                    break;
                                }
                                parseXml(MainActivity.this, new StringReader(response));
                                Log.d(LOG_TAG, "state=" + state);
                                Log.d(LOG_TAG, "connectionServiceUrl=" + connectionServiceUrl);
                                Log.d(LOG_TAG, "protocol=" + protocol);
                                try {
                                    Thread.sleep(1000);
                                } catch (Exception e) {
                                }
                            } while (state.equals(STATE_RUNNING) && connectionServiceUrl == null);

                            if (connectionServiceUrl == null) {
                                Log.i(LOG_TAG, "connectionServiceUrl is null");
                                return; // oops, something went wrong
                            }

                            // get the websocket URL
                            String webSocketAddress = null;
                            httpPost = new HttpPost(connectionServiceUrl); // "http://192.168.0.17:8008/connection/YouTube"
                            httpPost.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE);
                            httpPost.setHeader(HEADER_ORIGN, HEADER_ORIGIN_VALUE);
                            httpPost.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
                            httpPost.setHeader(HEADER_DNT, HEADER_DNT_VALUE);
                            httpPost.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE);
                            httpPost.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE);
                            httpPost.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE);
                            httpPost.setHeader(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_JSON_VALUE);
                            httpPost.setEntity(new StringEntity(
                                    "{\"channel\":0,\"senderId\":{\"appName\":\"ChromeCast\", \"senderId\":\"7v3zqrpliq3i\"}}"));

                            httpResponse = defaultHttpClient.execute(httpPost, localContext);
                            if (httpResponse != null) {
                                responseCode = httpResponse.getStatusLine().getStatusCode();
                                Log.d(LOG_TAG, "post response code=" + responseCode);
                                if (responseCode == 200) {
                                    // should return JSON payload
                                    response = EntityUtils.toString(httpResponse.getEntity());
                                    Log.d(LOG_TAG, "post response=" + response);
                                    Header[] headers = httpResponse.getAllHeaders();
                                    for (int i = 0; i < headers.length; i++) {
                                        Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue());
                                    }

                                    JSONObject jObject;
                                    try {
                                        jObject = new JSONObject(response); // {"URL":"ws://192.168.0.17:8008/session?33","pingInterval":0}
                                        webSocketAddress = jObject.getString("URL");
                                        Log.d(LOG_TAG, "webSocketAddress: " + webSocketAddress);
                                        int pingInterval = jObject.optInt("pingInterval"); // TODO
                                    } catch (JSONException e) {
                                        Log.e(LOG_TAG, "JSON", e);
                                    }
                                }
                            } else {
                                Log.i(LOG_TAG, "no post response");
                                return;
                            }

                            // Make a web socket connection for doing RAMP
                            // to control media playback
                            if (webSocketAddress != null) {
                                // https://github.com/koush/android-websockets
                                List<BasicNameValuePair> extraHeaders = Arrays.asList(
                                        new BasicNameValuePair(HEADER_ORIGN, HEADER_ORIGIN_VALUE),
                                        new BasicNameValuePair("Pragma", "no-cache"),
                                        new BasicNameValuePair("Cache-Control", "no-cache"),
                                        new BasicNameValuePair(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE));
                                client = new WebSocketClient(URI.create(webSocketAddress),
                                        new WebSocketClient.Listener() { // ws://192.168.0.17:8008/session?26
                                            @Override
                                            public void onConnect() {
                                                Log.d(LOG_TAG, "Websocket Connected!");

                                                // TODO RAMP commands
                                            }

                                            @Override
                                            public void onMessage(String message) {
                                                Log.d(LOG_TAG, String.format("Websocket Got string message! %s",
                                                        message));
                                            }

                                            @Override
                                            public void onMessage(byte[] data) {
                                                Log.d(LOG_TAG, String.format("Websocket Got binary message! %s",
                                                        data));
                                            }

                                            @Override
                                            public void onDisconnect(int code, String reason) {
                                                Log.d(LOG_TAG,
                                                        String.format(
                                                                "Websocket Disconnected! Code: %d Reason: %s",
                                                                code, reason));
                                            }

                                            @Override
                                            public void onError(Exception error) {
                                                Log.e(LOG_TAG, "Websocket Error!", error);
                                            }

                                        }, extraHeaders);
                                client.connect();
                            } else {
                                Log.i(LOG_TAG, "webSocketAddress is null");
                            }

                        } catch (Exception e) {
                            Log.e(LOG_TAG, "run", e);
                        }
                    }
                }).start();
            }
        }
    }
}

From source file:org.catnut.metadata.WeiboAPIError.java

/**
 * volley?/* ww w.java 2 s .com*/
 *
 * @param volleyError
 * @return WeiboAPIError
 */
public static WeiboAPIError fromVolleyError(VolleyError volleyError) {
    // very bad situation!
    if (volleyError.networkResponse == null) {
        String message = volleyError.getLocalizedMessage();
        return new WeiboAPIError(-1, null,
                TextUtils.isEmpty(message) ? volleyError.getClass().getName() : message);
    }
    // ?response body
    String jsonString;
    try {
        jsonString = new String(volleyError.networkResponse.data);
    } catch (Exception e) {
        Log.wtf(TAG, e);
        // fall back to http error!
        String msg = volleyError.getLocalizedMessage();
        return new WeiboAPIError(volleyError.networkResponse.statusCode, null,
                TextUtils.isEmpty(msg) ? "Unknown error! Please try again later:-(" : msg);
    }

    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        return new WeiboAPIError(jsonObject.optInt(ERROR_CODE), jsonObject.optString(REQUEST),
                jsonObject.optString(ERROR));
    } catch (JSONException e) {
        Log.wtf(TAG, e.getLocalizedMessage());
    }
    // never happen?
    return null;
}