Example usage for android.net Uri encode

List of usage examples for android.net Uri encode

Introduction

In this page you can find the example usage for android.net Uri encode.

Prototype

public static String encode(String s) 

Source Link

Document

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme.

Usage

From source file:nya.miku.wishmaster.chans.newnullchan.NewNullchanModule.java

private String validateCaptcha(String captchaID, ProgressListener listener, CancellableTask task) {
    if (captchaID == null)
        return null;
    String captchaAnswer = captchas.get(captchaID);
    if (captchaAnswer == null)
        return null;
    String url = getUsingUrl() + "api/captcha?captcha=" + captchaID + "&answer=" + Uri.encode(captchaAnswer)
            + "&session=" + sessionId;
    JSONObject response = null;//w  w w.  ja v  a 2s.  co  m
    try {
        response = downloadJSONObject(url, false, listener, task);
    } catch (Exception e) {
        return null;
    }
    if (response == null)
        return null;
    if (!response.optBoolean("ok", false))
        return null;
    captchas.remove(captchaID);
    return captchaID;
}

From source file:org.thoughtcrime.securesms.contacts.ContactAccessor.java

/***
 * If the code below looks shitty to you, that's because it was taken
 * directly from the Android source, where shitty code is all you get.
 *//*from   www. ja v a2  s .c  om*/

public Cursor getCursorForRecipientFilter(CharSequence constraint, ContentResolver mContentResolver) {
    final String SORT_ORDER = Contacts.TIMES_CONTACTED + " DESC," + Contacts.DISPLAY_NAME + "," + Phone.TYPE;

    final String[] PROJECTION_PHONE = { Phone._ID, // 0
            Phone.CONTACT_ID, // 1
            Phone.TYPE, // 2
            Phone.NUMBER, // 3
            Phone.LABEL, // 4
            Phone.DISPLAY_NAME, // 5
    };

    String phone = "";
    String cons = null;

    if (constraint != null) {
        cons = constraint.toString();

        if (RecipientsAdapter.usefulAsDigits(cons)) {
            phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons);
            if (phone.equals(cons) && !PhoneNumberUtils.isWellFormedSmsAddress(phone)) {
                phone = "";
            } else {
                phone = phone.trim();
            }
        }
    }
    Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(cons));
    String selection = String.format("%s=%s OR %s=%s OR %s=%s", Phone.TYPE, Phone.TYPE_MOBILE, Phone.TYPE,
            Phone.TYPE_WORK_MOBILE, Phone.TYPE, Phone.TYPE_MMS);

    Cursor phoneCursor = mContentResolver.query(uri, PROJECTION_PHONE, null, null, SORT_ORDER);

    if (phone.length() > 0) {
        ArrayList result = new ArrayList();
        result.add(Integer.valueOf(-1)); // ID
        result.add(Long.valueOf(-1)); // CONTACT_ID
        result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE
        result.add(phone); // NUMBER

        /*
        * The "\u00A0" keeps Phone.getDisplayLabel() from deciding
        * to display the default label ("Home") next to the transformation
        * of the letters into numbers.
        */
        result.add("\u00A0"); // LABEL
        result.add(cons); // NAME

        ArrayList<ArrayList> wrap = new ArrayList<ArrayList>();
        wrap.add(result);

        ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap);

        return new MergeCursor(new Cursor[] { translated, phoneCursor });
    } else {
        return phoneCursor;
    }
}

From source file:com.android.music.AlbumBrowserFragment.java

private Cursor getAlbumCursor(AsyncQueryHandler async, String filter) {
    String[] cols = new String[] { MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ARTIST,
            MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ALBUM_ART };

    Cursor ret = null;/*from   www  .j av a 2s  . c  o m*/
    if (mArtistId != null) {
        Uri uri = MediaStore.Audio.Artists.Albums.getContentUri("external", Long.valueOf(mArtistId));
        if (!TextUtils.isEmpty(filter)) {
            uri = uri.buildUpon().appendQueryParameter("filter", Uri.encode(filter)).build();
        }
        if (async != null) {
            async.startQuery(0, null, uri, cols, null, null, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
        } else {
            ret = MusicUtils.query(getActivity(), uri, cols, null, null,
                    MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
        }
    } else {
        Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
        if (!TextUtils.isEmpty(filter)) {
            uri = uri.buildUpon().appendQueryParameter("filter", Uri.encode(filter)).build();
        }
        if (async != null) {
            async.startQuery(0, null, uri, cols, null, null, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
        } else {
            ret = MusicUtils.query(getActivity(), uri, cols, null, null,
                    MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
        }
    }
    return ret;
}

From source file:com.github.kanata3249.ffxieq.android.EquipmentSelectorActivity.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.EditAugment:
        if (mLongClickingItemIsCurrent)
            AugmentEditActivity.startActivity(this, 0, getFFXICharacter(), mPart, mLongClickingItemId, mAugID);
        else//  www. j av  a 2  s  . c  o  m
            AugmentEditActivity.startActivity(this, 0, getFFXICharacter(), mPart, mLongClickingItemId, -1);
        return true;
    }

    Equipment eq = getDAO().instantiateEquipment(mLongClickingItemId, -1);
    String name = eq.getName();
    Intent intent;
    if (eq != null) {
        String[] urls = getResources().getStringArray(R.array.SearchURIs);
        String url;

        url = null;
        switch (item.getItemId()) {
        case R.id.WebSearch0:
            url = urls[0];
            break;
        case R.id.WebSearch1:
            url = urls[1];
            break;
        case R.id.WebSearch2:
            url = urls[2];
            break;
        case R.id.WebSearch3:
            url = urls[3];
            break;
        case R.id.WebSearch4:
            url = urls[4];
            break;
        case R.id.WebSearch5:
            url = urls[5];
            break;
        case R.id.WebSearch6:
            url = urls[6];
            break;
        case R.id.WebSearch7:
            url = urls[7];
            break;
        default:
            url = null;
            break;
        }
        if (url != null) {
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + Uri.encode(name.split("[\\+?i]")[0])));
            startActivity(intent);
            return true;
        }
    }
    return super.onContextItemSelected(item);
}

From source file:com.github.kanata3249.ffxieq.android.AugmentSelectorActivity.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.EditAugment:
        if (mLongClickingItemId == -1)
            AugmentEditActivity.startActivity(this, 0, getFFXICharacter(), mPart, mCurrent, -1);
        else/*ww w. j av  a  2  s  .  c  o  m*/
            AugmentEditActivity.startActivity(this, 0, getFFXICharacter(), mPart, -1, mLongClickingItemId);
        return true;
    case R.id.DeleteAugment:
        showDialog(R.string.QueryDeleteAugment);
        return true;
    }

    Equipment eq = getDAO().instantiateEquipment(-1, mLongClickingItemId);
    Intent intent;
    if (eq != null) {
        String name = eq.getName();
        String[] urls = getResources().getStringArray(R.array.SearchURIs);
        String url;

        url = null;
        switch (item.getItemId()) {
        case R.id.WebSearch0:
            url = urls[0];
            break;
        case R.id.WebSearch1:
            url = urls[1];
            break;
        case R.id.WebSearch2:
            url = urls[2];
            break;
        case R.id.WebSearch3:
            url = urls[3];
            break;
        case R.id.WebSearch4:
            url = urls[4];
            break;
        case R.id.WebSearch5:
            url = urls[5];
            break;
        case R.id.WebSearch6:
            url = urls[6];
            break;
        case R.id.WebSearch7:
            url = urls[7];
            break;
        default:
            url = null;
            break;
        }
        if (url != null) {
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + Uri.encode(name.split("[\\+?i]")[0])));
            startActivity(intent);
            return true;
        }
    }
    return super.onContextItemSelected(item);
}

From source file:com.android.dialer.calllog.ContactInfoHelper.java

/**
 * Parses the given URI to determine the original lookup key of the contact.
 *//*  w  w  w.  j  a v  a2s  . c  o m*/
public static String getLookupKeyFromUri(Uri lookupUri) {
    // Would be nice to be able to persist the lookup key somehow to avoid having to parse
    // the uri entirely just to retrieve the lookup key, but every uri is already parsed
    // once anyway to check if it is an encoded JSON uri, so this has negligible effect
    // on performance.
    if (lookupUri != null && !UriUtils.isEncodedContactUri(lookupUri)) {
        final List<String> segments = lookupUri.getPathSegments();
        // This returns the third path segment of the uri, where the lookup key is located.
        // See {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI}.
        return (segments.size() < 3) ? null : Uri.encode(segments.get(2));
    } else {
        return null;
    }
}

From source file:com.securecomcode.text.contacts.ContactAccessor.java

/***
 * If the code below looks shitty to you, that's because it was taken
 * directly from the Android source, where shitty code is all you get.
 *//*w  w w  .  j  a  v  a  2 s  .c om*/

public Cursor getCursorForRecipientFilter(CharSequence constraint, ContentResolver mContentResolver) {
    final String SORT_ORDER = Contacts.TIMES_CONTACTED + " DESC," + Contacts.DISPLAY_NAME + ","
            + Contacts.Data.IS_SUPER_PRIMARY + " DESC," + Phone.TYPE;

    final String[] PROJECTION_PHONE = { Phone._ID, // 0
            Phone.CONTACT_ID, // 1
            Phone.TYPE, // 2
            Phone.NUMBER, // 3
            Phone.LABEL, // 4
            Phone.DISPLAY_NAME, // 5
    };

    String phone = "";
    String cons = null;

    if (constraint != null) {
        cons = constraint.toString();

        if (RecipientsAdapter.usefulAsDigits(cons)) {
            phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons);
            if (phone.equals(cons) && !PhoneNumberUtils.isWellFormedSmsAddress(phone)) {
                phone = "";
            } else {
                phone = phone.trim();
            }
        }
    }
    Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(cons));
    String selection = String.format("%s=%s OR %s=%s OR %s=%s", Phone.TYPE, Phone.TYPE_MOBILE, Phone.TYPE,
            Phone.TYPE_WORK_MOBILE, Phone.TYPE, Phone.TYPE_MMS);

    Cursor phoneCursor = mContentResolver.query(uri, PROJECTION_PHONE, null, null, SORT_ORDER);

    if (phone.length() > 0) {
        ArrayList result = new ArrayList();
        result.add(Integer.valueOf(-1)); // ID
        result.add(Long.valueOf(-1)); // CONTACT_ID
        result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE
        result.add(phone); // NUMBER

        /*
        * The "\u00A0" keeps Phone.getDisplayLabel() from deciding
        * to display the default label ("Home") next to the transformation
        * of the letters into numbers.
        */
        result.add("\u00A0"); // LABEL
        result.add(cons); // NAME

        ArrayList<ArrayList> wrap = new ArrayList<ArrayList>();
        wrap.add(result);

        ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap);

        return new MergeCursor(new Cursor[] { translated, phoneCursor });
    } else {
        return phoneCursor;
    }
}

From source file:com.necisstudio.highlightgoal.MainActivity.java

void drawermenu(int id) {
    if (id == R.id.rate) {
        Uri uri = Uri.parse("market://details?id=com.necisstudio.highlightgoal");
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
                | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        try {//www.j a v  a 2 s  .c  o  m
            startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://play.google.com/store/apps/details?id=com.necisstudio.highlightgoal")));
        }

    } else if (id == R.id.feedback) {
        Intent send = new Intent(Intent.ACTION_SENDTO);
        String uriText = "mailto:" + Uri.encode("report@necistudio.com") + "?subject="
                + Uri.encode("Feedback for Highlight Goal") + "&body=" + Uri.encode("");
        Uri uri = Uri.parse(uriText);
        send.setData(uri);
        startActivity(Intent.createChooser(send, "Send mail..."));
    } else if (id == R.id.latest) {
        ApplicationConfig.status = id;
        iddrawer = id;
        imgLogo.setImageResource(0);
        txtTitle.setText("Latest");
        fList = new ArrayList<Fragment>();
        List<Fragment> fragments = getFragments(HighlightLatestFragment.newInstance(""),
                KlasementLigaFragment.newInstance("inggris"), ScheduleLigaLatestFragment.newInstance(""));
        adapter_viewPager = new Adapter_ViewPager(getSupportFragmentManager(), fragments);
        final ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        tabHost = (TabLayout) findViewById(R.id.materialTabHost);
        pager.setAdapter(adapter_viewPager);
        pager.setOffscreenPageLimit(3);
        tabHost.setupWithViewPager(pager);
        tabHost.getTabAt(0).setText("Highlight");
        tabHost.getTabAt(1).setText("Schedule");
    } else if (id == R.id.inggris) {
        ApplicationConfig.status = id;
        iddrawer = id;
        imgLogo.setImageResource(R.mipmap.premier);
        txtTitle.setText("Premier League");
        fList = new ArrayList<Fragment>();
        List<Fragment> fragments = getFragments(HighlightFragment.newInstance("inggris"),
                KlasementLigaFragment.newInstance("inggris"), ScheduleLigaFragment.newInstance("inggris"));
        adapter_viewPager = new Adapter_ViewPager(getSupportFragmentManager(), fragments);
        final ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        tabHost = (TabLayout) findViewById(R.id.materialTabHost);
        pager.setAdapter(adapter_viewPager);
        pager.setOffscreenPageLimit(3);

        tabHost.setupWithViewPager(pager);
        tabHost.getTabAt(0).setText("Highlight");
        tabHost.getTabAt(1).setText("Standings");
        tabHost.getTabAt(2).setText("Schedule");

    } else if (id == R.id.europa) {
        ApplicationConfig.status = id;
        iddrawer = id;
        imgLogo.setImageResource(R.mipmap.europa);
        txtTitle.setText("Europa League");
        fList = new ArrayList<Fragment>();
        List<Fragment> fragments = getFragments(HighlightFragment.newInstance("europa"),
                new TeamEuropaFragment(), ScheduleLigaFragment.newInstance("europa"));
        adapter_viewPager = new Adapter_ViewPager(getSupportFragmentManager(), fragments);
        final ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        tabHost = (TabLayout) findViewById(R.id.materialTabHost);
        pager.setAdapter(adapter_viewPager);
        pager.setOffscreenPageLimit(3);

        tabHost.setupWithViewPager(pager);
        tabHost.getTabAt(0).setText("Highlight");
        tabHost.getTabAt(1).setText("Standings");
        tabHost.getTabAt(2).setText("Schedule");
    } else if (id == R.id.champion) {
        ApplicationConfig.status = id;
        iddrawer = id;
        imgLogo.setImageResource(R.mipmap.champion);
        txtTitle.setText("Champions League");
        fList = new ArrayList<Fragment>();
        List<Fragment> fragments = getFragments(HighlightFragment.newInstance("champions"),
                new TeamChampionsFragment(), ScheduleLigaFragment.newInstance("champions"));
        adapter_viewPager = new Adapter_ViewPager(getSupportFragmentManager(), fragments);
        final ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        tabHost = (TabLayout) findViewById(R.id.materialTabHost);
        pager.setAdapter(adapter_viewPager);
        pager.setOffscreenPageLimit(3);

        tabHost.setupWithViewPager(pager);
        tabHost.getTabAt(0).setText("Highlight");
        tabHost.getTabAt(1).setText("Standings");
        tabHost.getTabAt(2).setText("Schedule");
    } else if (id == R.id.seria) {
        ApplicationConfig.status = id;
        iddrawer = id;
        imgLogo.setImageResource(R.mipmap.seria);
        txtTitle.setText("Seri A");
        fList = new ArrayList<Fragment>();
        List<Fragment> fragments = getFragments(HighlightFragment.newInstance("italia"),
                KlasementLigaFragment.newInstance("italia"), ScheduleLigaFragment.newInstance("italia"));
        adapter_viewPager = new Adapter_ViewPager(getSupportFragmentManager(), fragments);
        final ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        tabHost = (TabLayout) findViewById(R.id.materialTabHost);
        pager.setAdapter(adapter_viewPager);
        pager.setOffscreenPageLimit(3);

        tabHost.setupWithViewPager(pager);
        tabHost.getTabAt(0).setText("Highlight");
        tabHost.getTabAt(1).setText("Standings");
        tabHost.getTabAt(2).setText("Schedule");
    } else if (id == R.id.jerman) {
        ApplicationConfig.status = id;
        iddrawer = id;
        imgLogo.setImageResource(R.mipmap.bundes);
        txtTitle.setText("Bundesliga");
        fList = new ArrayList<Fragment>();
        List<Fragment> fragments = getFragments(HighlightFragment.newInstance("jerman"),
                KlasementLigaFragment.newInstance("jerman"), ScheduleLigaFragment.newInstance("jerman"));
        adapter_viewPager = new Adapter_ViewPager(getSupportFragmentManager(), fragments);
        final ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        tabHost = (TabLayout) findViewById(R.id.materialTabHost);
        pager.setAdapter(adapter_viewPager);
        pager.setOffscreenPageLimit(3);

        tabHost.setupWithViewPager(pager);
        tabHost.getTabAt(0).setText("Highlight");
        tabHost.getTabAt(1).setText("Standings");
        tabHost.getTabAt(2).setText("Schedule");
    } else if (id == R.id.spain) {
        ApplicationConfig.status = id;
        iddrawer = id;
        imgLogo.setImageResource(R.mipmap.bbva);
        txtTitle.setText("BBVA League");
        fList = new ArrayList<Fragment>();
        List<Fragment> fragments = getFragments(HighlightFragment.newInstance("spain"),
                KlasementLigaFragment.newInstance("spain"), ScheduleLigaFragment.newInstance("spain"));
        adapter_viewPager = new Adapter_ViewPager(getSupportFragmentManager(), fragments);
        final ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        tabHost = (TabLayout) findViewById(R.id.materialTabHost);
        pager.setAdapter(adapter_viewPager);
        pager.setOffscreenPageLimit(3);

        tabHost.setupWithViewPager(pager);
        tabHost.getTabAt(0).setText("Highlight");
        tabHost.getTabAt(1).setText("Standings");
        tabHost.getTabAt(2).setText("Schedule");
    } else if (id == R.id.france) {
        ApplicationConfig.status = id;
        iddrawer = id;
        imgLogo.setImageResource(R.mipmap.ligue);
        txtTitle.setText("League 1");
        fList = new ArrayList<Fragment>();
        List<Fragment> fragments = getFragments(HighlightFragment.newInstance("france"),
                KlasementLigaFragment.newInstance("france"), ScheduleLigaFragment.newInstance("france"));
        adapter_viewPager = new Adapter_ViewPager(getSupportFragmentManager(), fragments);
        final ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        tabHost = (TabLayout) findViewById(R.id.materialTabHost);
        pager.setAdapter(adapter_viewPager);
        pager.setOffscreenPageLimit(3);

        tabHost.setupWithViewPager(pager);
        tabHost.getTabAt(0).setText("Highlight");
        tabHost.getTabAt(1).setText("Standings");
        tabHost.getTabAt(2).setText("Schedule");
    } else if (id == R.id.about) {
        Intent intent = new Intent(MainActivity.this, ActivityAbout.class);
        startActivity(intent);
    } else if (id == R.id.license) {
        Intent intent = new Intent(MainActivity.this, ActivityLicense.class);
        startActivity(intent);
    }
}

From source file:com.piusvelte.sonet.core.SonetComments.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if ((mMessage.getText().toString() != null) && (mMessage.getText().toString().length() > 0)
                && (mSid != null) && (mEsid != null)) {
            mMessage.setEnabled(false);/*  w  w  w .j  av a  2s.c o m*/
            mSend.setEnabled(false);
            // post or comment!
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() {
                @Override
                protected String doInBackground(Void... arg0) {
                    List<NameValuePair> params;
                    String message;
                    String response = null;
                    HttpPost httpPost;
                    SonetOAuth sonetOAuth;
                    String serviceName = Sonet.getServiceName(getResources(), mService);
                    publishProgress(serviceName);
                    switch (mService) {
                    case TWITTER:
                        // limit tweets to 140, breaking up the message if necessary
                        sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, mToken, mSecret);
                        message = mMessage.getText().toString();
                        while (message.length() > 0) {
                            final String send;
                            if (message.length() > 140) {
                                // need to break on a word
                                int end = 0;
                                int nextSpace = 0;
                                for (int i = 0, i2 = message.length(); i < i2; i++) {
                                    end = nextSpace;
                                    if (message.substring(i, i + 1).equals(" ")) {
                                        nextSpace = i;
                                    }
                                }
                                // in case there are no spaces, just break on 140
                                if (end == 0) {
                                    end = 140;
                                }
                                send = message.substring(0, end);
                                message = message.substring(end + 1);
                            } else {
                                send = message;
                                message = "";
                            }
                            httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL));
                            // resolve Error 417 Expectation by Twitter
                            httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                            params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair(Sstatus, send));
                            params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid));
                            try {
                                httpPost.setEntity(new UrlEncodedFormEntity(params));
                                response = SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        break;
                    case FACEBOOK:
                        httpPost = new HttpPost(String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid,
                                Saccess_token, mToken));
                        params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                        try {
                            httpPost.setEntity(new UrlEncodedFormEntity(params));
                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case MYSPACE:
                        sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET, mToken, mSecret);
                        try {
                            httpPost = new HttpPost(String.format(MYSPACE_URL_STATUSMOODCOMMENTS,
                                    MYSPACE_BASE_URL, mEsid, mSid));
                            httpPost.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOODCOMMENTS_BODY,
                                    mMessage.getText().toString())));
                            response = SonetHttpClient.httpResponse(mHttpClient,
                                    sonetOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case FOURSQUARE:
                        try {
                            message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                            httpPost = new HttpPost(String.format(FOURSQUARE_ADDCOMMENT, FOURSQUARE_BASE_URL,
                                    mSid, message, mToken));
                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case LINKEDIN:
                        sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mToken, mSecret);
                        try {
                            httpPost = new HttpPost(
                                    String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid));
                            httpPost.setEntity(new StringEntity(
                                    String.format(LINKEDIN_COMMENT_BODY, mMessage.getText().toString())));
                            httpPost.addHeader(new BasicHeader("Content-Type", "application/xml"));
                            response = SonetHttpClient.httpResponse(mHttpClient,
                                    sonetOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case IDENTICA:
                        // limit tweets to 140, breaking up the message if necessary
                        sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken, mSecret);
                        message = mMessage.getText().toString();
                        while (message.length() > 0) {
                            final String send;
                            if (message.length() > 140) {
                                // need to break on a word
                                int end = 0;
                                int nextSpace = 0;
                                for (int i = 0, i2 = message.length(); i < i2; i++) {
                                    end = nextSpace;
                                    if (message.substring(i, i + 1).equals(" ")) {
                                        nextSpace = i;
                                    }
                                }
                                // in case there are no spaces, just break on 140
                                if (end == 0) {
                                    end = 140;
                                }
                                send = message.substring(0, end);
                                message = message.substring(end + 1);
                            } else {
                                send = message;
                                message = "";
                            }
                            httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL));
                            // resolve Error 417 Expectation by Twitter
                            httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                            params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair(Sstatus, send));
                            params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid));
                            try {
                                httpPost.setEntity(new UrlEncodedFormEntity(params));
                                response = SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        break;
                    case GOOGLEPLUS:
                        break;
                    case CHATTER:
                        httpPost = new HttpPost(String.format(CHATTER_URL_COMMENT, mChatterInstance, mSid,
                                Uri.encode(mMessage.getText().toString())));
                        httpPost.setHeader("Authorization", "OAuth " + mChatterToken);
                        response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        break;
                    }
                    return ((response == null) && (mService == MYSPACE)) ? null
                            : serviceName + " "
                                    + getString(response != null ? R.string.success : R.string.failure);
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                }

                @Override
                protected void onPostExecute(String result) {
                    if (result != null) {
                        (Toast.makeText(SonetComments.this, result, Toast.LENGTH_LONG)).show();
                    } else if (mService == MYSPACE) {
                        // myspace permissions
                        (Toast.makeText(SonetComments.this,
                                SonetComments.this.getResources()
                                        .getStringArray(R.array.service_entries)[MYSPACE]
                                        + getString(R.string.failure) + " "
                                        + getString(R.string.myspace_permissions_message),
                                Toast.LENGTH_LONG)).show();
                    }
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    finish();
                }

            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            loadingDialog.show();
            asyncTask.execute();
        } else {
            (Toast.makeText(SonetComments.this, "error parsing message body", Toast.LENGTH_LONG)).show();
            mMessage.setEnabled(true);
            mSend.setEnabled(true);
        }
    }
}

From source file:com.piusvelte.sonet.SonetComments.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if ((mMessage.getText().toString() != null) && (mMessage.getText().toString().length() > 0)
                && (mSid != null) && (mEsid != null)) {
            mMessage.setEnabled(false);//w w w.j  a  v  a  2s  .com
            mSend.setEnabled(false);
            // post or comment!
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() {
                @Override
                protected String doInBackground(Void... arg0) {
                    List<NameValuePair> params;
                    String message;
                    String response = null;
                    HttpPost httpPost;
                    SonetOAuth sonetOAuth;
                    String serviceName = Sonet.getServiceName(getResources(), mService);
                    publishProgress(serviceName);
                    switch (mService) {
                    case TWITTER:
                        // limit tweets to 140, breaking up the message if necessary
                        sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET, mToken,
                                mSecret);
                        message = mMessage.getText().toString();
                        while (message.length() > 0) {
                            final String send;
                            if (message.length() > 140) {
                                // need to break on a word
                                int end = 0;
                                int nextSpace = 0;
                                for (int i = 0, i2 = message.length(); i < i2; i++) {
                                    end = nextSpace;
                                    if (message.substring(i, i + 1).equals(" ")) {
                                        nextSpace = i;
                                    }
                                }
                                // in case there are no spaces, just break on 140
                                if (end == 0) {
                                    end = 140;
                                }
                                send = message.substring(0, end);
                                message = message.substring(end + 1);
                            } else {
                                send = message;
                                message = "";
                            }
                            httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL));
                            // resolve Error 417 Expectation by Twitter
                            httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                            params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair(Sstatus, send));
                            params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid));
                            try {
                                httpPost.setEntity(new UrlEncodedFormEntity(params));
                                response = SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        break;
                    case FACEBOOK:
                        httpPost = new HttpPost(String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid,
                                Saccess_token, mToken));
                        params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                        try {
                            httpPost.setEntity(new UrlEncodedFormEntity(params));
                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case MYSPACE:
                        sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET, mToken,
                                mSecret);
                        try {
                            httpPost = new HttpPost(String.format(MYSPACE_URL_STATUSMOODCOMMENTS,
                                    MYSPACE_BASE_URL, mEsid, mSid));
                            httpPost.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOODCOMMENTS_BODY,
                                    mMessage.getText().toString())));
                            response = SonetHttpClient.httpResponse(mHttpClient,
                                    sonetOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case FOURSQUARE:
                        try {
                            message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                            httpPost = new HttpPost(String.format(FOURSQUARE_ADDCOMMENT, FOURSQUARE_BASE_URL,
                                    mSid, message, mToken));
                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case LINKEDIN:
                        sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET,
                                mToken, mSecret);
                        try {
                            httpPost = new HttpPost(
                                    String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid));
                            httpPost.setEntity(new StringEntity(
                                    String.format(LINKEDIN_COMMENT_BODY, mMessage.getText().toString())));
                            httpPost.addHeader(new BasicHeader("Content-Type", "application/xml"));
                            response = SonetHttpClient.httpResponse(mHttpClient,
                                    sonetOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case IDENTICA:
                        // limit tweets to 140, breaking up the message if necessary
                        sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET,
                                mToken, mSecret);
                        message = mMessage.getText().toString();
                        while (message.length() > 0) {
                            final String send;
                            if (message.length() > 140) {
                                // need to break on a word
                                int end = 0;
                                int nextSpace = 0;
                                for (int i = 0, i2 = message.length(); i < i2; i++) {
                                    end = nextSpace;
                                    if (message.substring(i, i + 1).equals(" ")) {
                                        nextSpace = i;
                                    }
                                }
                                // in case there are no spaces, just break on 140
                                if (end == 0) {
                                    end = 140;
                                }
                                send = message.substring(0, end);
                                message = message.substring(end + 1);
                            } else {
                                send = message;
                                message = "";
                            }
                            httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL));
                            // resolve Error 417 Expectation by Twitter
                            httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                            params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair(Sstatus, send));
                            params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid));
                            try {
                                httpPost.setEntity(new UrlEncodedFormEntity(params));
                                response = SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        break;
                    case GOOGLEPLUS:
                        break;
                    case CHATTER:
                        httpPost = new HttpPost(String.format(CHATTER_URL_COMMENT, mChatterInstance, mSid,
                                Uri.encode(mMessage.getText().toString())));
                        httpPost.setHeader("Authorization", "OAuth " + mChatterToken);
                        response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                        break;
                    }
                    return ((response == null) && (mService == MYSPACE)) ? null
                            : serviceName + " "
                                    + getString(response != null ? R.string.success : R.string.failure);
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                }

                @Override
                protected void onPostExecute(String result) {
                    if (result != null) {
                        (Toast.makeText(SonetComments.this, result, Toast.LENGTH_LONG)).show();
                    } else if (mService == MYSPACE) {
                        // myspace permissions
                        (Toast.makeText(SonetComments.this,
                                SonetComments.this.getResources()
                                        .getStringArray(R.array.service_entries)[MYSPACE]
                                        + getString(R.string.failure) + " "
                                        + getString(R.string.myspace_permissions_message),
                                Toast.LENGTH_LONG)).show();
                    }
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    finish();
                }

            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            loadingDialog.show();
            asyncTask.execute();
        } else {
            (Toast.makeText(SonetComments.this, "error parsing message body", Toast.LENGTH_LONG)).show();
            mMessage.setEnabled(true);
            mSend.setEnabled(true);
        }
    }
}