Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

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

Prototype

public JSONObject(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:de.blinkt.openvpn.fragments.AboutFragment.java

private void createPlayBuyOptions(ArrayList<String> ownedSkus, ArrayList<String> responseList) {
    try {/*from  w  w w  .  j ava2  s  .  c  o m*/
        Vector<Pair<String, String>> gdonation = new Vector<Pair<String, String>>();

        gdonation.add(new Pair<String, String>(getString(R.string.donatePlayStore), null));
        HashMap<String, SkuResponse> responseMap = new HashMap<String, SkuResponse>();
        for (String thisResponse : responseList) {
            JSONObject object = new JSONObject(thisResponse);
            responseMap.put(object.getString("productId"),
                    new SkuResponse(object.getString("price"), object.getString("title")));

        }
        for (String sku : donationSkus)
            if (responseMap.containsKey(sku))
                gdonation.add(
                        getSkuTitle(sku, responseMap.get(sku).title, responseMap.get(sku).price, ownedSkus));

        String gmsTextString = "";
        for (int i = 0; i < gdonation.size(); i++) {
            if (i == 1)
                gmsTextString += "  ";
            else if (i > 1)
                gmsTextString += ", ";
            gmsTextString += gdonation.elementAt(i).first;
        }
        SpannableString gmsText = new SpannableString(gmsTextString);

        int lStart = 0;
        int lEnd = 0;
        for (Pair<String, String> item : gdonation) {
            lEnd = lStart + item.first.length();
            if (item.second != null) {
                final String mSku = item.second;
                ClickableSpan cspan = new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        triggerBuy(mSku);
                    }
                };
                gmsText.setSpan(cspan, lStart, lEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            lStart = lEnd + 2; // Account for ", " between items
        }

        if (gmsTextView != null) {
            gmsTextView.setText(gmsText);
            gmsTextView.setMovementMethod(LinkMovementMethod.getInstance());
            gmsTextView.setVisibility(View.VISIBLE);
        }

    } catch (JSONException e) {
        VpnStatus.logException("Parsing Play Store IAP", e);
    }

}

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

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // ??*_*?view?
    String query = CatnutUtils.buildQuery(PROJECTION, User.screen_name + "=" + CatnutUtils.quote(mScreenName),
            User.TABLE, null, null, null);
    new AsyncQueryHandler(getActivity().getContentResolver()) {
        @Override/*  w ww. j a  v a 2 s .c  o m*/
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            if (cursor.moveToNext()) {
                injectProfile(cursor);
            } else {
                // fall back to load from network...
                mApp.getRequestQueue().add(new CatnutRequest(getActivity(), UserAPI.profile(mScreenName),
                        new UserProcessor.UserProfileProcessor(), new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                injectProfile(response);
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(getActivity(), getString(R.string.user_not_found),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }));
            }
            cursor.close();
        }
    }.startQuery(0, null, CatnutProvider.parse(User.MULTIPLE), null, query, null, null);
    // ??
    if (mApp.getPreferences().getBoolean(getString(R.string.pref_show_latest_tweet), true)) {
        String queryLatestTweet = CatnutUtils.buildQuery(new String[] { Status.columnText,
                //                     Status.thumbnail_pic,
                Status.bmiddle_pic, Status.comments_count, Status.reposts_count, Status.retweeted_status,
                Status.attitudes_count, Status.source, Status.created_at, },
                new StringBuilder("uid=(select _id from ").append(User.TABLE).append(" where ")
                        .append(User.screen_name).append("=").append(CatnutUtils.quote(mScreenName)).append(")")
                        .append(" and ").append(Status.TYPE).append(" in(").append(Status.HOME).append(",")
                        .append(Status.RETWEET).append(",").append(Status.OTHERS).append(")").toString(),
                Status.TABLE, null, BaseColumns._ID + " desc", "1");
        new AsyncQueryHandler(getActivity().getContentResolver()) {
            @Override
            protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
                if (cursor.moveToNext()) {
                    mTweetLayout.setOnClickListener(tweetsOnclickListener);
                    ViewStub viewStub = (ViewStub) mTweetLayout.findViewById(R.id.latest_tweet);
                    View tweet = viewStub.inflate();
                    mRetweetLayout = tweet.findViewById(R.id.retweet);
                    tweet.findViewById(R.id.timeline).setVisibility(View.GONE);
                    tweet.findViewById(R.id.verified).setVisibility(View.GONE);
                    tweet.findViewById(R.id.tweet_overflow).setVisibility(View.GONE);
                    CatnutUtils.setText(tweet, R.id.nick, getString(R.string.latest_statues))
                            .setTextColor(getResources().getColor(R.color.actionbar_background));
                    String tweetText = cursor.getString(cursor.getColumnIndex(Status.columnText));
                    TweetImageSpan tweetImageSpan = new TweetImageSpan(getActivity());
                    TweetTextView text = (TweetTextView) CatnutUtils.setText(tweet, R.id.text,
                            tweetImageSpan.getImageSpan(tweetText));
                    CatnutUtils.vividTweet(text, null);
                    CatnutUtils.setTypeface(text, mTypeface);
                    text.setLineSpacing(0, mLineSpacing);

                    String thumbsUrl = cursor.getString(cursor.getColumnIndex(Status.bmiddle_pic));
                    if (!TextUtils.isEmpty(thumbsUrl)) {
                        View thumbs = tweet.findViewById(R.id.thumbs);
                        Picasso.with(getActivity()).load(thumbsUrl).placeholder(R.drawable.error)
                                .error(R.drawable.error).into((ImageView) thumbs);
                        thumbs.setVisibility(View.VISIBLE);
                    }

                    int replyCount = cursor.getInt(cursor.getColumnIndex(Status.comments_count));
                    CatnutUtils.setText(tweet, R.id.reply_count, CatnutUtils.approximate(replyCount));
                    int retweetCount = cursor.getInt(cursor.getColumnIndex(Status.reposts_count));
                    CatnutUtils.setText(tweet, R.id.reteet_count, CatnutUtils.approximate(retweetCount));
                    int favoriteCount = cursor.getInt(cursor.getColumnIndex(Status.attitudes_count));
                    CatnutUtils.setText(tweet, R.id.like_count, CatnutUtils.approximate(favoriteCount));
                    String source = cursor.getString(cursor.getColumnIndex(Status.source));
                    CatnutUtils.setText(tweet, R.id.source, Html.fromHtml(source).toString());
                    String create_at = cursor.getString(cursor.getColumnIndex(Status.created_at));
                    CatnutUtils
                            .setText(tweet, R.id.create_at,
                                    DateUtils.getRelativeTimeSpanString(DateTime.getTimeMills(create_at)))
                            .setVisibility(View.VISIBLE);
                    // retweet
                    final String jsonString = cursor.getString(cursor.getColumnIndex(Status.retweeted_status));
                    try {
                        JSONObject jsonObject = new JSONObject(jsonString);
                        TweetTextView retweet = (TweetTextView) mRetweetLayout.findViewById(R.id.retweet_text);
                        retweet.setText(jsonObject.optString(Status.text));
                        CatnutUtils.vividTweet(retweet, tweetImageSpan);
                        CatnutUtils.setTypeface(retweet, mTypeface);
                        retweet.setLineSpacing(0, mLineSpacing);
                        long mills = DateTime.getTimeMills(jsonObject.optString(Status.created_at));
                        TextView tv = (TextView) mRetweetLayout.findViewById(R.id.retweet_create_at);
                        tv.setText(DateUtils.getRelativeTimeSpanString(mills));
                        TextView retweetUserScreenName = (TextView) mRetweetLayout
                                .findViewById(R.id.retweet_nick);
                        JSONObject user = jsonObject.optJSONObject(User.SINGLE);
                        if (user == null) {
                            retweetUserScreenName.setText(getString(R.string.unknown_user));
                        } else {
                            retweetUserScreenName.setText(user.optString(User.screen_name));
                            mRetweetLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(getActivity(), TweetActivity.class);
                                    intent.putExtra(Constants.JSON, jsonString);
                                    startActivity(intent);
                                }
                            });
                        }
                    } catch (Exception e) {
                        mRetweetLayout.setVisibility(View.GONE);
                    }
                }
                cursor.close();
            }
        }.startQuery(0, null, CatnutProvider.parse(Status.MULTIPLE), null, queryLatestTweet, null, null);
    }
}

From source file:com.fabernovel.alertevoirie.webservice.HttpPostRequest.java

public String sendRequest() throws AVServiceErrorException {
    try {/*ww w.j a  v a2  s. c om*/

        httpPost = new HttpPost(url);

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 20000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

        httpPost.addHeader(HEADER_APP_VERSION, "1.0.0");
        httpPost.addHeader(HEADER_APP_PLATFORM, "android_family");
        httpPost.addHeader(HEADER_APP_DEVICE_MODEL, (Build.MANUFACTURER + " " + Build.DEVICE).trim());
        httpPost.addHeader(HEADER_APP_REQUEST_SIGNATURE, sha1(MAGIC_KEY + params.get(0).getValue()));

        // Log.i(Constants.PROJECT_TAG,MAGIC_KEY + params.get(0).getValue());

        final HttpResponse response = httpClient.execute(httpPost);
        final HttpEntity entity = response.getEntity();
        content = entity.getContent();
        contentString = convertStreamToString(content);
        Log.d(Constants.PROJECT_TAG, "answer = " + contentString);
    } catch (final UnsupportedEncodingException uee) {
        Log.e(Constants.PROJECT_TAG, "UnsupportedEncodingException", uee);
        throw new AVServiceErrorException(999);
    } catch (final IOException ioe) {
        Log.e(Constants.PROJECT_TAG, "IOException", ioe);
        throw new AVServiceErrorException(999);
    } catch (final IllegalStateException ise) {
        Log.e(Constants.PROJECT_TAG, "IllegalStateException", ise);
        throw new AVServiceErrorException(999);
    } catch (NoSuchAlgorithmException e) {
        Log.e(Constants.PROJECT_TAG, "NoSuchAlgorithmException", e);
        throw new AVServiceErrorException(999);
    } catch (Exception e) {
        Log.e(Constants.PROJECT_TAG, "error in sendRequest : ", e);
        throw new AVServiceErrorException(999);
    }

    try {

        Log.d(Constants.PROJECT_TAG, "contenString: " + contentString);
        JSONObject jo = new JSONObject(contentString);
        int resultnum = jo.getJSONObject(JsonData.PARAM_ANSWER).getInt(JsonData.PARAM_STATUS);
        Log.i(Constants.PROJECT_TAG, "AV Status:" + resultnum);
        if (resultnum != 0)
            throw new AVServiceErrorException(resultnum);

    } catch (JSONException e) {
        Log.w(Constants.PROJECT_TAG, "JSONException in onPostExecute");
        //throw new AVServiceErrorException(999);
    }

    return contentString;
}

From source file:org.droidparts.test.testcase.serialize.AbstractJSONTestCase.java

protected final JSONObject getJSONObject(int resId) throws Exception {
    return new JSONObject(getJSONString(resId));
}

From source file:com.nextgis.firereporter.SettingsSupport.java

public SettingsSupport(Context context, PreferenceScreen screen) {
    this.screen = screen;
    this.context = context;

    // Load the preferences from an XML resource
    //addPreferencesFromResource(R.xml.preferences);

    mSendDataIntervalPref = (ListPreference) screen.findPreference(SettingsActivity.KEY_PREF_INTERVAL);
    if (mSendDataIntervalPref != null) {
        int index = mSendDataIntervalPref.findIndexOfValue(mSendDataIntervalPref.getValue());
        if (index >= 0) {
            mSendDataIntervalPref.setSummary(mSendDataIntervalPref.getEntries()[index]);
        } else {/*from w  w  w . j  ava2  s . c o  m*/
            mSendDataIntervalPref.setSummary((String) mSendDataIntervalPref.getValue());
        }
    }

    mSaveBattPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_SERVICE_BATT_SAVE);
    if (mSaveBattPref != null)
        mSaveBattPref.setSummary(mSaveBattPref.isChecked() ? R.string.stOn : R.string.stOff);

    mNotifyLEDPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_NOTIFY_LED);
    if (mNotifyLEDPref != null)
        mNotifyLEDPref.setSummary(mNotifyLEDPref.isChecked() ? R.string.stOn : R.string.stOff);

    mPlaySoundPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_NOTIFY_SOUND);
    if (mPlaySoundPref != null)
        mPlaySoundPref.setSummary(mPlaySoundPref.isChecked() ? R.string.stOn : R.string.stOff);

    mVibroPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_NOTIFY_VIBRO);
    if (mVibroPref != null)
        mVibroPref.setSummary(mVibroPref.isChecked() ? R.string.stOn : R.string.stOff);

    mRowCountPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_ROW_COUNT);
    if (mRowCountPref != null)
        mRowCountPref.setSummary((String) mRowCountPref.getText());

    mFireSearchRadiusPref = (EditTextPreference) screen
            .findPreference(SettingsActivity.KEY_PREF_FIRE_SEARCH_RADIUS);
    if (mFireSearchRadiusPref != null)
        mFireSearchRadiusPref
                .setSummary((String) mFireSearchRadiusPref.getText() + " " + context.getString(R.string.km));

    mDayIntervalPref = (ListPreference) screen.findPreference(SettingsActivity.KEY_PREF_SEARCH_DAY_INTERVAL);
    if (mDayIntervalPref != null) {
        int index = mDayIntervalPref.findIndexOfValue(mDayIntervalPref.getValue());
        if (index >= 0) {
            mDayIntervalPref.setSummary(mDayIntervalPref.getEntries()[index]);
        } else {
            mDayIntervalPref.setSummary((String) mDayIntervalPref.getValue());
        }
    }

    mSearchCurrentDatePref = (CheckBoxPreference) screen
            .findPreference(SettingsActivity.KEY_PREF_SEARCH_CURR_DAY);
    if (mSearchCurrentDatePref != null)
        mSearchCurrentDatePref.setSummary(mSearchCurrentDatePref.isChecked() ? R.string.stSearchCurrentDayOn
                : R.string.stSearchCurrentDayOff);

    mNasaServerPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_NASA);
    if (mNasaServerPref != null)
        mNasaServerPref.setSummary((String) mNasaServerPref.getText());
    mNasaServerUserPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_NASA_USER);
    if (mNasaServerUserPref != null)
        mNasaServerUserPref.setSummary((String) mNasaServerUserPref.getText());

    mUserServerPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_USER);
    if (mUserServerPref != null)
        mUserServerPref.setSummary((String) mUserServerPref.getText());
    mUserServerUserPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_USER_USER);
    if (mUserServerUserPref != null)
        mUserServerUserPref.setSummary((String) mUserServerUserPref.getText());

    mScanServerUserPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_SCAN_USER);
    if (mScanServerUserPref != null)
        mScanServerUserPref.setSummary((String) mScanServerUserPref.getText());

    mNasaServerPassPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_NASA_PASS);
    mUserServerPassPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_USER_PASS);
    mScanServerPassPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_SCAN_PASS);

    final Preference checkNasaConnPref = (Preference) screen
            .findPreference(SettingsActivity.KEY_PREF_SRV_NASA_CHECK_CONN);
    final Preference checkUserConnPref = (Preference) screen
            .findPreference(SettingsActivity.KEY_PREF_SRV_USER_CHECK_CONN);
    final Preference checkScanConnPref = (Preference) screen
            .findPreference(SettingsActivity.KEY_PREF_SRV_SCAN_CHECK_CONN);

    mReturnHandler = new Handler() {
        @SuppressLint("NewApi")
        public void handleMessage(Message msg) {
            Bundle resultData = msg.getData();

            boolean bHaveErr = resultData.getBoolean(GetFiresService.ERROR);
            int nType = resultData.getInt(GetFiresService.SOURCE);
            if (bHaveErr) {
                Toast.makeText(SettingsSupport.this.context, resultData.getString(GetFiresService.ERR_MSG),
                        Toast.LENGTH_LONG).show();
                if (nType == 1) {//user
                    checkUserConnPref.setSummary(R.string.stConnectionFailed);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        checkUserConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                } else if (nType == 2) {//nasa
                    checkNasaConnPref.setSummary(R.string.stConnectionFailed);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        checkNasaConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                } else if (nType == 3) {//scanex
                    checkScanConnPref.setSummary(R.string.stConnectionFailed);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        checkScanConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                }
            } else {

                String sData = resultData.getString(GetFiresService.JSON);
                if (nType == 1) {//user
                    JSONObject jsonMainObject;
                    try {
                        jsonMainObject = new JSONObject(sData);
                        if (jsonMainObject.getBoolean("error")) {
                            String sMsg = jsonMainObject.getString("msg");
                            Toast.makeText(SettingsSupport.this.context, sMsg, Toast.LENGTH_LONG).show();
                            checkUserConnPref.setSummary(R.string.stConnectionFailed);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkUserConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                        } else {
                            checkUserConnPref.setSummary(R.string.stConnectionSucceeded);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkUserConnPref.setIcon(R.drawable.ic_navigation_accept);
                        }
                    } catch (JSONException e) {
                        Toast.makeText(SettingsSupport.this.context, e.toString(), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                        checkUserConnPref.setSummary(R.string.sCheckDBConnSummary);
                    }
                } else if (nType == 2) {//nasa
                    JSONObject jsonMainObject;
                    try {
                        jsonMainObject = new JSONObject(sData);
                        if (jsonMainObject.getBoolean("error")) {
                            String sMsg = jsonMainObject.getString("msg");
                            Toast.makeText(SettingsSupport.this.context, sMsg, Toast.LENGTH_LONG).show();
                            checkNasaConnPref.setSummary(R.string.stConnectionFailed);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkNasaConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                        } else {
                            checkNasaConnPref.setSummary(R.string.stConnectionSucceeded);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkNasaConnPref.setIcon(R.drawable.ic_navigation_accept);
                        }
                    } catch (JSONException e) {
                        Toast.makeText(SettingsSupport.this.context, e.toString(), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                        checkNasaConnPref.setSummary(R.string.sCheckDBConnSummary);
                    }
                } else if (nType == 3) {//scanex
                    if (sData.length() == 0) {
                        String sMsg = "Connect failed";
                        Toast.makeText(SettingsSupport.this.context, sMsg, Toast.LENGTH_LONG).show();
                        checkScanConnPref.setSummary(R.string.stConnectionFailed);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                            checkScanConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                    } else {
                        checkScanConnPref.setSummary(R.string.stConnectionSucceeded);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                            checkScanConnPref.setIcon(R.drawable.ic_navigation_accept);

                        new HttpGetter(SettingsSupport.this.context, 4,
                                SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler,
                                true).execute(
                                        "http://fires.kosmosnimki.ru/SAPI/Account/Get/?CallBackName="
                                                + GetFiresService.USER_ID,
                                        sData);
                    }
                } else if (nType == 4) {//scanex detailes
                    try {
                        String sSubData = GetFiresService.removeJsonT(sData);
                        JSONObject rootobj = new JSONObject(sSubData);
                        String sStatus = rootobj.getString("Status");
                        if (sStatus.equals("OK")) {
                            JSONObject resobj = rootobj.getJSONObject("Result");
                            String sName = "";
                            if (!resobj.isNull("FullName"))
                                sName = resobj.getString("FullName");
                            String sPhone = "";
                            if (!resobj.isNull("Phone"))
                                sPhone = resobj.getString("Phone");
                            //add properties
                            if (sPhone.length() > 0) {
                                Preference PhonePref = new Preference(SettingsSupport.this.context);
                                PhonePref.setTitle(R.string.stScanexServerUserPhone);
                                PhonePref.setSummary(sPhone);
                                PhonePref.setOrder(2);
                                SettingsSupport.this.screen.addPreference(PhonePref);
                            }

                            if (sName.length() > 0) {
                                Preference NamePref = new Preference(SettingsSupport.this.context);
                                NamePref.setTitle(R.string.stScanexServerUserFullName);
                                NamePref.setSummary(sName);
                                NamePref.setOrder(2);
                                SettingsSupport.this.screen.addPreference(NamePref);
                            }

                        } else {
                            Toast.makeText(SettingsSupport.this.context, rootobj.getString("ErrorInfo"),
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        Toast.makeText(SettingsSupport.this.context, e.toString(), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }
            }
        };
    };

    if (checkNasaConnPref != null)
        checkNasaConnPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                String sURL = mNasaServerPref.getText() + "?function=test_conn_nasa&user="
                        + mNasaServerUserPref.getText() + "&pass=" + mNasaServerPassPref.getText();
                new HttpGetter(SettingsSupport.this.context, 2,
                        SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler, true)
                                .execute(sURL);
                return true;
            }
        });

    if (checkUserConnPref != null)
        checkUserConnPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                String sURL = mUserServerPref.getText() + "?function=test_conn_user&user="
                        + mUserServerUserPref.getText() + "&pass=" + mUserServerPassPref.getText();
                new HttpGetter(SettingsSupport.this.context, 1,
                        SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler, true)
                                .execute(sURL);
                return true;
            }
        });

    if (checkScanConnPref != null)
        checkScanConnPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                //String sURL = mUserServerPref.getText() + "?function=test_conn_nasa&user=" + mUserServerUserPref.getText() + "&pass=" + mUserServerPassPref.getText();
                new ScanexHttpLogin(SettingsSupport.this.context, 3,
                        SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler, true)
                                .execute(mScanServerUserPref.getText(), mScanServerPassPref.getText());
                return true;
            }
        });
}

From source file:org.uiautomation.ios.grid.IOSCapabilitiesMonitor.java

private static JSONObject extractObject(HttpResponse resp) throws IOException, JSONException {
    BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    StringBuilder s = new StringBuilder();
    String line;//from  w  w  w.jav a 2s.com
    while ((line = rd.readLine()) != null) {
        s.append(line);
    }
    rd.close();
    return new JSONObject(s.toString());
}

From source file:com.facebook.internal.LikeActionController.java

private static LikeActionController deserializeFromJson(String controllerJsonString) {
    LikeActionController controller;/*ww w .  j a v a2s. c  o  m*/

    try {
        JSONObject controllerJson = new JSONObject(controllerJsonString);
        int version = controllerJson.optInt(JSON_INT_VERSION_KEY, -1);
        if (version != LIKE_ACTION_CONTROLLER_VERSION) {
            // Don't attempt to deserialize a controller that might be serialized differently than expected.
            return null;
        }

        controller = new LikeActionController(Session.getActiveSession(),
                controllerJson.getString(JSON_STRING_OBJECT_ID_KEY));

        // Make sure to default to null and not empty string, to keep the logic elsewhere functioning properly.
        controller.likeCountStringWithLike = controllerJson.optString(JSON_STRING_LIKE_COUNT_WITH_LIKE_KEY,
                null);
        controller.likeCountStringWithoutLike = controllerJson
                .optString(JSON_STRING_LIKE_COUNT_WITHOUT_LIKE_KEY, null);
        controller.socialSentenceWithLike = controllerJson.optString(JSON_STRING_SOCIAL_SENTENCE_WITH_LIKE_KEY,
                null);
        controller.socialSentenceWithoutLike = controllerJson
                .optString(JSON_STRING_SOCIAL_SENTENCE_WITHOUT_LIKE_KEY, null);
        controller.isObjectLiked = controllerJson.optBoolean(JSON_BOOL_IS_OBJECT_LIKED_KEY);
        controller.unlikeToken = controllerJson.optString(JSON_STRING_UNLIKE_TOKEN_KEY, null);
        String pendingCallIdString = controllerJson.optString(JSON_STRING_PENDING_CALL_ID_KEY, null);
        if (!Utility.isNullOrEmpty(pendingCallIdString)) {
            controller.pendingCallId = UUID.fromString(pendingCallIdString);
        }

        JSONObject analyticsJSON = controllerJson.optJSONObject(JSON_BUNDLE_PENDING_CALL_ANALYTICS_BUNDLE);
        if (analyticsJSON != null) {
            controller.pendingCallAnalyticsBundle = BundleJSONConverter.convertToBundle(analyticsJSON);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Unable to deserialize controller from JSON", e);
        controller = null;
    }

    return controller;
}

From source file:com.citrus.mobile.RESTclient.java

public JSONObject makeWithdrawRequest(String accessToken, double amount, String currency, String owner,
        String accountNumber, String ifscCode) {
    HttpsURLConnection conn;//from w w  w .  j  a v a 2s . c om
    DataOutputStream wr = null;
    JSONObject txnDetails = null;
    BufferedReader in = null;

    try {
        String url = urls.getString(base_url) + urls.getString(type);

        conn = (HttpsURLConnection) new URL(url).openConnection();

        //add reuqest header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);

        StringBuffer buff = new StringBuffer("amount=");
        buff.append(amount);

        buff.append("&currency=");
        buff.append(currency);

        buff.append("&owner=");
        buff.append(owner);

        buff.append("&account=");
        buff.append(accountNumber);

        buff.append("&ifsc=");
        buff.append(ifscCode);

        conn.setDoOutput(true);
        wr = new DataOutputStream(conn.getOutputStream());

        wr.writeBytes(buff.toString());
        wr.flush();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + buff.toString());
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        txnDetails = new JSONObject(response.toString());

    } catch (JSONException exception) {
        exception.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            if (wr != null) {
                wr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return txnDetails;
}