Example usage for android.app ProgressDialog show

List of usage examples for android.app ProgressDialog show

Introduction

In this page you can find the example usage for android.app ProgressDialog show.

Prototype

public void show() 

Source Link

Document

Start the dialog and display it on screen.

Usage

From source file:fm.smart.r1.ItemActivity.java

public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // this should be called once image has been chosen by user
    // using requestCode to pass item id - haven't worked out any other way
    // to do it/*from  w ww .  j a  v  a2 s  .  c  om*/
    // if (requestCode == SELECT_IMAGE)
    if (resultCode == Activity.RESULT_OK) {
        // TODO check if user is logged in
        if (LoginActivity.isNotLoggedIn(this)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClassName(this, LoginActivity.class.getName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            // avoid navigation back to this?
            LoginActivity.return_to = ItemActivity.class.getName();
            LoginActivity.params = new HashMap<String, String>();
            LoginActivity.params.put("item_id", (String) item.getId());
            startActivity(intent);
            // TODO in this case forcing the user to rechoose the image
            // seems a little
            // rude - should probably auto-submit here ...
        } else {
            // Bundle extras = data.getExtras();
            // String sentence_id = (String) extras.get("sentence_id");
            final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
            myOtherProgressDialog.setTitle("Please Wait ...");
            myOtherProgressDialog.setMessage("Uploading image ...");
            myOtherProgressDialog.setIndeterminate(true);
            myOtherProgressDialog.setCancelable(true);

            final Thread add_image = new Thread() {
                public void run() {
                    // TODO needs to check for interruptibility

                    String sentence_id = Integer.toString(requestCode);
                    Uri selectedImage = data.getData();
                    // Bitmap bitmap = Media.getBitmap(getContentResolver(),
                    // selectedImage);
                    // ByteArrayOutputStream bytes = new
                    // ByteArrayOutputStream();
                    // bitmap.compress(Bitmap.CompressFormat.JPEG, 40,
                    // bytes);
                    // ByteArrayInputStream fileInputStream = new
                    // ByteArrayInputStream(
                    // bytes.toByteArray());

                    // TODO Might have to save to file system first to get
                    // this
                    // to work,
                    // argh!
                    // could think of it as saving to cache ...

                    // add image to sentence
                    FileInputStream is = null;
                    FileOutputStream os = null;
                    File file = null;
                    ContentResolver resolver = getContentResolver();
                    try {
                        Bitmap bitmap = Media.getBitmap(getContentResolver(), selectedImage);
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
                        // ByteArrayInputStream bais = new
                        // ByteArrayInputStream(bytes.toByteArray());

                        // FileDescriptor fd =
                        // resolver.openFileDescriptor(selectedImage,
                        // "r").getFileDescriptor();
                        // is = new FileInputStream(fd);

                        String filename = "test.jpg";
                        File dir = ItemActivity.this.getDir("images", MODE_WORLD_READABLE);
                        file = new File(dir, filename);
                        os = new FileOutputStream(file);

                        // while (bais.available() > 0) {
                        // / os.write(bais.read());
                        // }
                        os.write(bytes.toByteArray());

                        os.close();

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        if (os != null) {
                            try {
                                os.close();
                            } catch (IOException e) {
                            }
                        }
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                            }
                        }
                    }

                    // File file = new
                    // File(Uri.decode(selectedImage.toString()));

                    // ensure item is in users default list

                    ItemActivity.add_item_result = new AddItemResult(Main.lookup.addItemToGoal(Main.transport,
                            Main.default_study_goal_id, item.getId(), null));

                    Result result = ItemActivity.add_item_result;

                    if (ItemActivity.add_item_result.success()
                            || ItemActivity.add_item_result.alreadyInList()) {

                        // ensure sentence is in users default goal

                        ItemActivity.add_sentence_goal_result = new AddSentenceResult(
                                Main.lookup.addSentenceToGoal(Main.transport, Main.default_study_goal_id,
                                        item.getId(), sentence_id, null));

                        result = ItemActivity.add_sentence_goal_result;
                        if (ItemActivity.add_sentence_goal_result.success()) {

                            String media_entity = "http://test.com/test.jpg";
                            String author = "tansaku";
                            String author_url = "http://smart.fm/users/tansaku";
                            Log.d("DEBUG-IMAGE-URI", selectedImage.toString());
                            ItemActivity.add_image_result = addImage(file, media_entity, author, author_url,
                                    "1", sentence_id, (String) item.getId(), Main.default_study_goal_id);
                            result = ItemActivity.add_image_result;
                        }
                    }
                    final Result display = result;
                    myOtherProgressDialog.dismiss();
                    ItemActivity.this.runOnUiThread(new Thread() {
                        public void run() {
                            final AlertDialog dialog = new AlertDialog.Builder(ItemActivity.this).create();
                            dialog.setTitle(display.getTitle());
                            dialog.setMessage(display.getMessage());
                            dialog.setButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    if (ItemActivity.add_image_result != null
                                            && ItemActivity.add_image_result.success()) {
                                        ItemListActivity.loadItem(ItemActivity.this, item.getId().toString());
                                    }
                                }
                            });

                            dialog.show();
                        }
                    });

                }

            };

            myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    add_image.interrupt();
                }
            });
            OnCancelListener ocl = new OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    add_image.interrupt();
                }
            };
            myOtherProgressDialog.setOnCancelListener(ocl);
            closeMenu();
            myOtherProgressDialog.show();
            add_image.start();

        }
    }
}

From source file:fm.smart.r1.activity.ItemActivity.java

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // this should be called once image has been chosen by user
    // using requestCode to pass item id - haven't worked out any other way
    // to do it//ww  w.j a v  a2s. com
    // if (requestCode == SELECT_IMAGE)
    if (resultCode == Activity.RESULT_OK) {
        // TODO check if user is logged in
        if (Main.isNotLoggedIn(this)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClassName(this, LoginActivity.class.getName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            // avoid navigation back to this?
            LoginActivity.return_to = ItemActivity.class.getName();
            LoginActivity.params = new HashMap<String, String>();
            LoginActivity.params.put("item_id", (String) item.item_node.atts.get("id"));
            startActivity(intent);
            // TODO in this case forcing the user to rechoose the image
            // seems a little
            // rude - should probably auto-submit here ...
        } else {
            // Bundle extras = data.getExtras();
            // String sentence_id = (String) extras.get("sentence_id");
            final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
            myOtherProgressDialog.setTitle("Please Wait ...");
            myOtherProgressDialog.setMessage("Uploading image ...");
            myOtherProgressDialog.setIndeterminate(true);
            myOtherProgressDialog.setCancelable(true);

            final Thread add_image = new Thread() {
                public void run() {
                    // TODO needs to check for interruptibility

                    String sentence_id = Integer.toString(requestCode);
                    Uri selectedImage = data.getData();
                    // Bitmap bitmap = Media.getBitmap(getContentResolver(),
                    // selectedImage);
                    // ByteArrayOutputStream bytes = new
                    // ByteArrayOutputStream();
                    // bitmap.compress(Bitmap.CompressFormat.JPEG, 40,
                    // bytes);
                    // ByteArrayInputStream fileInputStream = new
                    // ByteArrayInputStream(
                    // bytes.toByteArray());

                    // TODO Might have to save to file system first to get
                    // this
                    // to work,
                    // argh!
                    // could think of it as saving to cache ...

                    // add image to sentence
                    FileInputStream is = null;
                    FileOutputStream os = null;
                    File file = null;
                    ContentResolver resolver = getContentResolver();
                    try {
                        Bitmap bitmap = Media.getBitmap(getContentResolver(), selectedImage);
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
                        // ByteArrayInputStream bais = new
                        // ByteArrayInputStream(bytes.toByteArray());

                        // FileDescriptor fd =
                        // resolver.openFileDescriptor(selectedImage,
                        // "r").getFileDescriptor();
                        // is = new FileInputStream(fd);

                        String filename = "test.jpg";
                        File dir = ItemActivity.this.getDir("images", MODE_WORLD_READABLE);
                        file = new File(dir, filename);
                        os = new FileOutputStream(file);

                        // while (bais.available() > 0) {
                        // / os.write(bais.read());
                        // }
                        os.write(bytes.toByteArray());

                        os.close();

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        if (os != null) {
                            try {
                                os.close();
                            } catch (IOException e) {
                            }
                        }
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                            }
                        }
                    }

                    // File file = new
                    // File(Uri.decode(selectedImage.toString()));

                    // ensure item is in users default list

                    ItemActivity.add_item_result = addItemToList(Main.default_study_list_id,
                            (String) item.item_node.atts.get("id"), ItemActivity.this);
                    Result result = ItemActivity.add_item_result;

                    if (ItemActivity.add_item_result.success()
                            || ItemActivity.add_item_result.alreadyInList()) {

                        // ensure sentence is in users default list

                        ItemActivity.add_sentence_list_result = addSentenceToList(sentence_id,
                                (String) item.item_node.atts.get("id"), Main.default_study_list_id,
                                ItemActivity.this);
                        result = ItemActivity.add_sentence_list_result;
                        if (ItemActivity.add_sentence_list_result.success()) {

                            String media_entity = "http://test.com/test.jpg";
                            String author = "tansaku";
                            String author_url = "http://smart.fm/users/tansaku";
                            Log.d("DEBUG-IMAGE-URI", selectedImage.toString());
                            ItemActivity.add_image_result = addImage(file, media_entity, author, author_url,
                                    "1", sentence_id, (String) item.item_node.atts.get("id"),
                                    Main.default_study_list_id);
                            result = ItemActivity.add_image_result;
                        }
                    }
                    final Result display = result;
                    myOtherProgressDialog.dismiss();
                    ItemActivity.this.runOnUiThread(new Thread() {
                        public void run() {
                            final AlertDialog dialog = new AlertDialog.Builder(ItemActivity.this).create();
                            dialog.setTitle(display.getTitle());
                            dialog.setMessage(display.getMessage());
                            dialog.setButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    if (ItemActivity.add_image_result != null
                                            && ItemActivity.add_image_result.success()) {
                                        ItemListActivity.loadItem(ItemActivity.this,
                                                item.item_node.atts.get("id").toString());
                                    }
                                }
                            });

                            dialog.show();
                        }
                    });

                }

            };

            myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    add_image.interrupt();
                }
            });
            OnCancelListener ocl = new OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    add_image.interrupt();
                }
            };
            myOtherProgressDialog.setOnCancelListener(ocl);
            closeMenu();
            myOtherProgressDialog.show();
            add_image.start();

        }
    }
}

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

protected void loadFriends() {
    mFriends.clear();/*  w ww .j  a  v  a  2s  .c o m*/
    //      SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected});
    SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
            new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected });
    setListAdapter(sa);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() {
        @Override
        protected Boolean doInBackground(Long... params) {
            boolean loadList = false;
            SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext());
            // load the session
            Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this),
                    new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?",
                    new String[] { Long.toString(params[0]) }, null);
            if (account.moveToFirst()) {
                mToken = sonetCrypto.Decrypt(account.getString(0));
                mSecret = sonetCrypto.Decrypt(account.getString(1));
                mService = account.getInt(2);
            }
            account.close();
            String response;
            switch (mService) {
            case TWITTER:
                break;
            case FACEBOOK:
                if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                        String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) {
                    try {
                        JSONArray friends = new JSONObject(response).getJSONArray(Sdata);
                        for (int i = 0, l = friends.length(); i < l; i++) {
                            JSONObject f = friends.getJSONObject(i);
                            HashMap<String, String> newFriend = new HashMap<String, String>();
                            newFriend.put(Entities.ESID, f.getString(Sid));
                            newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid)));
                            newFriend.put(Entities.FRIEND, f.getString(Sname));
                            // need to alphabetize
                            if (mFriends.isEmpty())
                                mFriends.add(newFriend);
                            else {
                                String fullName = f.getString(Sname);
                                int spaceIdx = fullName.lastIndexOf(" ");
                                String newFirstName = null;
                                String newLastName = null;
                                if (spaceIdx == -1)
                                    newFirstName = fullName;
                                else {
                                    newFirstName = fullName.substring(0, spaceIdx++);
                                    newLastName = fullName.substring(spaceIdx);
                                }
                                List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>();
                                for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) {
                                    HashMap<String, String> oldFriend = mFriends.get(i2);
                                    if (newFriend == null) {
                                        newFriends.add(oldFriend);
                                    } else {
                                        fullName = oldFriend.get(Entities.FRIEND);
                                        spaceIdx = fullName.lastIndexOf(" ");
                                        String oldFirstName = null;
                                        String oldLastName = null;
                                        if (spaceIdx == -1)
                                            oldFirstName = fullName;
                                        else {
                                            oldFirstName = fullName.substring(0, spaceIdx++);
                                            oldLastName = fullName.substring(spaceIdx);
                                        }
                                        if (newFirstName == null) {
                                            newFriends.add(newFriend);
                                            newFriend = null;
                                        } else {
                                            int comparison = oldFirstName.compareToIgnoreCase(newFirstName);
                                            if (comparison == 0) {
                                                // compare firstnames
                                                if (newLastName == null) {
                                                    newFriends.add(newFriend);
                                                    newFriend = null;
                                                } else if (oldLastName != null) {
                                                    comparison = oldLastName.compareToIgnoreCase(newLastName);
                                                    if (comparison == 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    } else if (comparison > 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    }
                                                }
                                            } else if (comparison > 0) {
                                                newFriends.add(newFriend);
                                                newFriend = null;
                                            }
                                        }
                                        newFriends.add(oldFriend);
                                    }
                                }
                                if (newFriend != null)
                                    newFriends.add(newFriend);
                                mFriends = newFriends;
                            }
                        }
                        loadList = true;
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                }
                break;
            case MYSPACE:
                break;
            case LINKEDIN:
                break;
            case FOURSQUARE:
                break;
            case IDENTICA:
                break;
            case GOOGLEPLUS:
                break;
            case CHATTER:
                break;
            }
            return loadList;
        }

        @Override
        protected void onPostExecute(Boolean loadList) {
            if (loadList) {
                //               SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name});
                SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
                        new String[] { Entities.FRIEND, Entities.ESID },
                        new int[] { R.id.name, R.id.selected });
                sa.setViewBinder(mViewBinder);
                setListAdapter(sa);
            }
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }
    };
    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(mAccountId);
}

From source file:com.shafiq.myfeedle.core.SelectFriends.java

protected void loadFriends() {
    mFriends.clear();//www.  j  a  va2 s  .  c om
    //      SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected});
    SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
            new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected });
    setListAdapter(sa);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() {
        @Override
        protected Boolean doInBackground(Long... params) {
            boolean loadList = false;
            MyfeedleCrypto myfeedleCrypto = MyfeedleCrypto.getInstance(getApplicationContext());
            // load the session
            Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this),
                    new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?",
                    new String[] { Long.toString(params[0]) }, null);
            if (account.moveToFirst()) {
                mToken = myfeedleCrypto.Decrypt(account.getString(0));
                mSecret = myfeedleCrypto.Decrypt(account.getString(1));
                mService = account.getInt(2);
            }
            account.close();
            String response;
            switch (mService) {
            case TWITTER:
                break;
            case FACEBOOK:
                if ((response = MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(
                        String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) {
                    try {
                        JSONArray friends = new JSONObject(response).getJSONArray(Sdata);
                        for (int i = 0, l = friends.length(); i < l; i++) {
                            JSONObject f = friends.getJSONObject(i);
                            HashMap<String, String> newFriend = new HashMap<String, String>();
                            newFriend.put(Entities.ESID, f.getString(Sid));
                            newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid)));
                            newFriend.put(Entities.FRIEND, f.getString(Sname));
                            // need to alphabetize
                            if (mFriends.isEmpty())
                                mFriends.add(newFriend);
                            else {
                                String fullName = f.getString(Sname);
                                int spaceIdx = fullName.lastIndexOf(" ");
                                String newFirstName = null;
                                String newLastName = null;
                                if (spaceIdx == -1)
                                    newFirstName = fullName;
                                else {
                                    newFirstName = fullName.substring(0, spaceIdx++);
                                    newLastName = fullName.substring(spaceIdx);
                                }
                                List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>();
                                for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) {
                                    HashMap<String, String> oldFriend = mFriends.get(i2);
                                    if (newFriend == null) {
                                        newFriends.add(oldFriend);
                                    } else {
                                        fullName = oldFriend.get(Entities.FRIEND);
                                        spaceIdx = fullName.lastIndexOf(" ");
                                        String oldFirstName = null;
                                        String oldLastName = null;
                                        if (spaceIdx == -1)
                                            oldFirstName = fullName;
                                        else {
                                            oldFirstName = fullName.substring(0, spaceIdx++);
                                            oldLastName = fullName.substring(spaceIdx);
                                        }
                                        if (newFirstName == null) {
                                            newFriends.add(newFriend);
                                            newFriend = null;
                                        } else {
                                            int comparison = oldFirstName.compareToIgnoreCase(newFirstName);
                                            if (comparison == 0) {
                                                // compare firstnames
                                                if (newLastName == null) {
                                                    newFriends.add(newFriend);
                                                    newFriend = null;
                                                } else if (oldLastName != null) {
                                                    comparison = oldLastName.compareToIgnoreCase(newLastName);
                                                    if (comparison == 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    } else if (comparison > 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    }
                                                }
                                            } else if (comparison > 0) {
                                                newFriends.add(newFriend);
                                                newFriend = null;
                                            }
                                        }
                                        newFriends.add(oldFriend);
                                    }
                                }
                                if (newFriend != null)
                                    newFriends.add(newFriend);
                                mFriends = newFriends;
                            }
                        }
                        loadList = true;
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                }
                break;
            case MYSPACE:
                break;
            case LINKEDIN:
                break;
            case FOURSQUARE:
                break;
            case IDENTICA:
                break;
            case GOOGLEPLUS:
                break;
            case CHATTER:
                break;
            }
            return loadList;
        }

        @Override
        protected void onPostExecute(Boolean loadList) {
            if (loadList) {
                //               SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name});
                SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
                        new String[] { Entities.FRIEND, Entities.ESID },
                        new int[] { R.id.name, R.id.selected });
                sa.setViewBinder(mViewBinder);
                setListAdapter(sa);
            }
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }
    };
    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(mAccountId);
}

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

private void setLocation(final long accountId) {
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {

        int serviceId;

        @Override/* ww  w .ja va  2s .  co  m*/
        protected String doInBackground(Void... none) {
            Cursor account = getContentResolver().query(Accounts.getContentUri(SonetCreatePost.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET },
                    Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
            if (account.moveToFirst()) {
                SonetOAuth sonetOAuth;
                serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE));
                switch (serviceId) {
                case TWITTER:
                    // anonymous requests are rate limited to 150 per hour
                    // authenticated requests are rate limited to 350 per hour, so authenticate this!
                    sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
                    return SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong))));
                case FACEBOOK:
                    return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_SEARCH,
                            FACEBOOK_BASE_URL, mLat, mLong, Saccess_token,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                case FOURSQUARE:
                    return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(
                            FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                }
            }
            account.close();
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
            if (response != null) {
                switch (serviceId) {
                case TWITTER:
                    try {
                        JSONArray places = new JSONObject(response).getJSONObject(Sresult)
                                .getJSONArray(Splaces);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sfull_name);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FACEBOOK:
                    try {
                        JSONArray places = new JSONObject(response).getJSONArray(Sdata);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sname);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FOURSQUARE:
                    try {
                        JSONArray groups = new JSONObject(response).getJSONObject(Sresponse)
                                .getJSONArray(Sgroups);
                        for (int g = 0, g2 = groups.length(); g < g2; g++) {
                            JSONObject group = groups.getJSONObject(g);
                            if (group.getString(Sname).equals(SNearby)) {
                                JSONArray places = group.getJSONArray(Sitems);
                                final String placesNames[] = new String[places.length()];
                                final String placesIds[] = new String[places.length()];
                                for (int i = 0, i2 = places.length(); i < i2; i++) {
                                    JSONObject place = places.getJSONObject(i);
                                    placesNames[i] = place.getString(Sname);
                                    placesIds[i] = place.getString(Sid);
                                }
                                mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                        .setSingleChoiceItems(placesNames, -1,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        mAccountsLocation.put(accountId, placesIds[which]);
                                                        dialog.dismiss();
                                                    }
                                                })
                                        .setNegativeButton(android.R.string.cancel,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .create();
                                mDialog.show();
                                break;
                            }
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                }
            } else {
                (Toast.makeText(SonetCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG)).show();
            }
        }

    };
    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();
}

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

private void setLocation(final long accountId) {
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {

        int serviceId;

        @Override/*from   w w  w.j ava2s  . c o m*/
        protected String doInBackground(Void... none) {
            Cursor account = getContentResolver().query(Accounts.getContentUri(SonetCreatePost.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET },
                    Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
            if (account.moveToFirst()) {
                SonetOAuth sonetOAuth;
                serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE));
                switch (serviceId) {
                case TWITTER:
                    // anonymous requests are rate limited to 150 per hour
                    // authenticated requests are rate limited to 350 per hour, so authenticate this!
                    sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
                    return SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong))));
                case FACEBOOK:
                    return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_SEARCH,
                            FACEBOOK_BASE_URL, mLat, mLong, Saccess_token,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                case FOURSQUARE:
                    return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(
                            FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                }
            }
            account.close();
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
            if (response != null) {
                switch (serviceId) {
                case TWITTER:
                    try {
                        JSONArray places = new JSONObject(response).getJSONObject(Sresult)
                                .getJSONArray(Splaces);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sfull_name);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FACEBOOK:
                    try {
                        JSONArray places = new JSONObject(response).getJSONArray(Sdata);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sname);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FOURSQUARE:
                    try {
                        JSONArray groups = new JSONObject(response).getJSONObject(Sresponse)
                                .getJSONArray(Sgroups);
                        for (int g = 0, g2 = groups.length(); g < g2; g++) {
                            JSONObject group = groups.getJSONObject(g);
                            if (group.getString(Sname).equals(SNearby)) {
                                JSONArray places = group.getJSONArray(Sitems);
                                final String placesNames[] = new String[places.length()];
                                final String placesIds[] = new String[places.length()];
                                for (int i = 0, i2 = places.length(); i < i2; i++) {
                                    JSONObject place = places.getJSONObject(i);
                                    placesNames[i] = place.getString(Sname);
                                    placesIds[i] = place.getString(Sid);
                                }
                                mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                        .setSingleChoiceItems(placesNames, -1,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        mAccountsLocation.put(accountId, placesIds[which]);
                                                        dialog.dismiss();
                                                    }
                                                })
                                        .setNegativeButton(android.R.string.cancel,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .create();
                                mDialog.show();
                                break;
                            }
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                }
            } else {
                (Toast.makeText(SonetCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG)).show();
            }
        }

    };
    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();
}

From source file:com.shafiq.myfeedle.core.MyfeedleCreatePost.java

private void setLocation(final long accountId) {
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {

        int serviceId;

        @Override//w  w w  . j a v a 2s  .c  o m
        protected String doInBackground(Void... none) {
            Cursor account = getContentResolver().query(Accounts.getContentUri(MyfeedleCreatePost.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET },
                    Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
            if (account.moveToFirst()) {
                MyfeedleOAuth myfeedleOAuth;
                serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE));
                switch (serviceId) {
                case TWITTER:
                    // anonymous requests are rate limited to 150 per hour
                    // authenticated requests are rate limited to 350 per hour, so authenticate this!
                    myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET,
                            mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                            mMyfeedleCrypto
                                    .Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
                    return MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(
                            new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong))));
                case FACEBOOK:
                    return MyfeedleHttpClient.httpResponse(mHttpClient,
                            new HttpGet(String.format(FACEBOOK_SEARCH, FACEBOOK_BASE_URL, mLat, mLong,
                                    Saccess_token, mMyfeedleCrypto.Decrypt(
                                            account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                case FOURSQUARE:
                    return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(
                            String.format(FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong, mMyfeedleCrypto
                                    .Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                }
            }
            account.close();
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
            if (response != null) {
                switch (serviceId) {
                case TWITTER:
                    try {
                        JSONArray places = new JSONObject(response).getJSONObject(Sresult)
                                .getJSONArray(Splaces);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sfull_name);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(MyfeedleCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FACEBOOK:
                    try {
                        JSONArray places = new JSONObject(response).getJSONArray(Sdata);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sname);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(MyfeedleCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FOURSQUARE:
                    try {
                        JSONArray groups = new JSONObject(response).getJSONObject(Sresponse)
                                .getJSONArray(Sgroups);
                        for (int g = 0, g2 = groups.length(); g < g2; g++) {
                            JSONObject group = groups.getJSONObject(g);
                            if (group.getString(Sname).equals(SNearby)) {
                                JSONArray places = group.getJSONArray(Sitems);
                                final String placesNames[] = new String[places.length()];
                                final String placesIds[] = new String[places.length()];
                                for (int i = 0, i2 = places.length(); i < i2; i++) {
                                    JSONObject place = places.getJSONObject(i);
                                    placesNames[i] = place.getString(Sname);
                                    placesIds[i] = place.getString(Sid);
                                }
                                mDialog = (new AlertDialog.Builder(MyfeedleCreatePost.this))
                                        .setSingleChoiceItems(placesNames, -1,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        mAccountsLocation.put(accountId, placesIds[which]);
                                                        dialog.dismiss();
                                                    }
                                                })
                                        .setNegativeButton(android.R.string.cancel,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .create();
                                mDialog.show();
                                break;
                            }
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                }
            } else {
                (Toast.makeText(MyfeedleCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG))
                        .show();
            }
        }

    };
    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();
}

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);/*from   ww w .j a va 2  s  . 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.shafiq.myfeedle.core.MyfeedleComments.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);/* ww  w  . j a va 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;
                    MyfeedleOAuth myfeedleOAuth;
                    String serviceName = Myfeedle.getServiceName(getResources(), mService);
                    publishProgress(serviceName);
                    switch (mService) {
                    case TWITTER:
                        // limit tweets to 140, breaking up the message if necessary
                        myfeedleOAuth = new MyfeedleOAuth(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 = MyfeedleHttpClient.httpResponse(mHttpClient,
                                        myfeedleOAuth.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 = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case MYSPACE:
                        myfeedleOAuth = new MyfeedleOAuth(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 = MyfeedleHttpClient.httpResponse(mHttpClient,
                                    myfeedleOAuth.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 = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                        } catch (UnsupportedEncodingException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case LINKEDIN:
                        myfeedleOAuth = new MyfeedleOAuth(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 = MyfeedleHttpClient.httpResponse(mHttpClient,
                                    myfeedleOAuth.getSignedRequest(httpPost));
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        }
                        break;
                    case IDENTICA:
                        // limit tweets to 140, breaking up the message if necessary
                        myfeedleOAuth = new MyfeedleOAuth(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 = MyfeedleHttpClient.httpResponse(mHttpClient,
                                        myfeedleOAuth.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 = MyfeedleHttpClient.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(MyfeedleComments.this, result, Toast.LENGTH_LONG)).show();
                    } else if (mService == MYSPACE) {
                        // myspace permissions
                        (Toast.makeText(MyfeedleComments.this,
                                MyfeedleComments.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(MyfeedleComments.this, "error parsing message body", Toast.LENGTH_LONG)).show();
            mMessage.setEnabled(true);
            mSend.setEnabled(true);
        }
    }
}