Example usage for android.app ProgressDialog setOnCancelListener

List of usage examples for android.app ProgressDialog setOnCancelListener

Introduction

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

Prototype

public void setOnCancelListener(@Nullable OnCancelListener listener) 

Source Link

Document

Set a listener to be invoked when the dialog is canceled.

Usage

From source file:net.nightwhistler.pageturner.activity.ReadingFragment.java

@Override
public void performSearch(String query) {

    LOG.debug("Starting search for: " + query);

    final ProgressDialog searchProgress = new ProgressDialog(context);
    searchProgress.setOwnerActivity(getActivity());
    searchProgress.setCancelable(true);/*  w ww .  j av  a 2s  . c o m*/
    searchProgress.setMax(100);
    searchProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

    final SearchTextTask task = new SearchTextTask(bookView.getBook()) {

        int i = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            searchProgress.setMessage(getString(R.string.search_wait));
            searchProgress.show();

            // Hide on-screen keyboard if it is showing
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

        }

        @Override
        protected void onProgressUpdate(SearchResult... values) {

            if (!isAdded()) {
                return;
            }

            super.onProgressUpdate(values);

            LOG.debug("Found match at index=" + values[0].getIndex() + ", offset=" + values[0].getStart()
                    + " with context " + values[0].getDisplay());
            SearchResult res = values[0];

            if (res.getDisplay() != null) {
                i++;
                String update = String.format(getString(R.string.search_hits), i);
                searchProgress.setMessage(update);
            }

            searchProgress.setProgress(bookView.getPercentageFor(res.getIndex(), res.getStart()));
        }

        @Override
        protected void onCancelled() {
            if (isAdded()) {
                Toast.makeText(context, R.string.search_cancelled, Toast.LENGTH_LONG).show();
            }
        }

        protected void onPostExecute(java.util.List<SearchResult> result) {

            searchProgress.dismiss();

            if (!isCancelled() && isAdded()) {
                if (result.size() > 0) {
                    searchResults = result;
                    showSearchResultDialog(result);
                } else {
                    Toast.makeText(context, R.string.search_no_matches, Toast.LENGTH_LONG).show();
                }
            }
        };
    };

    searchProgress.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            task.cancel(true);
        }
    });

    task.execute(query);
}

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

@Override
public void performSearch(String query) {

    LOG.debug("Starting search for: " + query);

    final ProgressDialog searchProgress = new ProgressDialog(context);
    searchProgress.setOwnerActivity(getActivity());
    searchProgress.setCancelable(true);//ww w  .  j av  a2 s. c o m
    searchProgress.setMax(100);
    searchProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

    final SearchTextTask task = new SearchTextTask(bookView.getBook()) {

        int i = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            searchProgress.setMessage(getString(R.string.search_wait));
            searchProgress.show();

            // Hide on-screen keyboard if it is showing
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

        }

        @Override
        protected void onProgressUpdate(SearchResult... values) {

            if (!isAdded()) {
                return;
            }

            super.onProgressUpdate(values);

            LOG.debug("Found match at index=" + values[0].getIndex() + ", offset=" + values[0].getStart()
                    + " with context " + values[0].getDisplay());
            SearchResult res = values[0];

            if (res.getDisplay() != null) {
                i++;
                String update = String.format(getString(R.string.search_hits), i);
                searchProgress.setMessage(update);
            }

            searchProgress.setProgress(bookView.getPercentageFor(res.getIndex(), res.getStart()));
        }

        @Override
        protected void onCancelled() {
            if (isAdded()) {
                Toast.makeText(context, R.string.search_cancelled, Toast.LENGTH_LONG).show();
            }
        }

        protected void onPostExecute(java.util.List<SearchResult> result) {

            searchProgress.dismiss();

            if (!isCancelled() && isAdded()) {
                if (result.size() > 0) {
                    searchResults = result;
                    searchResultWraper.setSearchResult(searchResults);

                    // showSearchResultDialog(result);
                    Intent intent = new Intent(getActivity(), ReadingOptionsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("SELECTED_TAB", 4);
                    intent.putExtras(bundle);
                    startActivity(intent);

                } else {
                    Toast.makeText(context, R.string.search_no_matches, Toast.LENGTH_LONG).show();
                }
            }
        };
    };

    searchProgress.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            task.cancel(true);
        }
    });

    task.execute(query);
}

From source file:com.dmsl.anyplace.UnifiedNavigationActivity.java

private void startNavigationTask(String id) {

    if (!NetworkUtils.isOnline(this)) {
        Toast.makeText(this, "No connection available!", Toast.LENGTH_SHORT).show();
        return;/*from  www  .j av a 2 s  . co m*/
    }

    // show the info window for the destination marker
    Marker marker = visiblePois.getMarkerFromPoisModel(id);
    if (marker != null) {
        marker.showInfoWindow();
    }

    final BuildingModel b = userData.getSelectedBuilding();
    final String floor = userData.getSelectedFloorNumber();

    class Status {
        Boolean task1 = false;
        Boolean task2 = false;
    }
    final Status status = new Status();

    final ProgressDialog dialog;
    dialog = new ProgressDialog(this);
    dialog.setIndeterminate(true);
    dialog.setTitle("Plotting navigation");
    dialog.setMessage("Please be patient...");
    dialog.setCancelable(true);
    dialog.setCanceledOnTouchOutside(false);

    GeoPoint entrance = null;
    GeoPoint pos = userData.getPositionWifi();
    if (pos == null) {
        // Find The nearest building entrance from the destination poi
        PoisModel _entrance = null;
        PoisModel dest = mAnyplaceCache.getPoisMap().get(id);
        double min = Double.MAX_VALUE;
        String currentFloor = userData.getSelectedFloorNumber();
        for (PoisModel pm : mAnyplaceCache.getPoisMap().values()) {
            if (pm.floor_number.equalsIgnoreCase(currentFloor) && pm.is_building_entrance) {
                double distance = Math.abs(pm.lat() - dest.lat()) + Math.abs(pm.lng() - dest.lng());
                if (min > distance) {
                    _entrance = pm;
                    min = distance;
                }
            }
        }

        if (_entrance != null) {
            entrance = new GeoPoint(_entrance.lat(), _entrance.lng());
        } else {
            Toast.makeText(this, "No entrance found!", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    final GeoPoint entrancef = entrance;

    // Does not run if entrance==null or is near the building
    final AsyncTask<Void, Void, String> async1f = new NavDirectionsTask(
            new NavDirectionsTask.NavDirectionsListener() {

                @Override
                public void onNavDirectionsSuccess(String result, List<LatLng> points) {
                    onNavDirectionsAboart();

                    if (!points.isEmpty()) {
                        // points.add(new LatLng(entrancef.dlat, entrancef.dlon));
                        pathLineOutsideOptions = new PolylineOptions().addAll(points).width(10).color(Color.RED)
                                .zIndex(100.0f);
                        pathLineOutside = mMap.addPolyline(pathLineOutsideOptions);
                    }
                }

                @Override
                public void onNavDirectionsErrorOrCancel(String result) {
                    onNavDirectionsAboart();
                    // display the error cause
                    Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onNavDirectionsAboart() {
                    status.task1 = true;
                    if (status.task1 && status.task2)
                        dialog.dismiss();
                    else {
                        // First task executed calls this
                        clearLastNavigationInfo();
                    }
                }

            }, userData.getLocationGPSorIP(), entrance);

    // start the navigation task
    final AsyncTask<Void, Void, String> async2f = new NavRouteTask(new NavRouteTask.NavRouteListener() {
        @Override
        public void onNavRouteSuccess(String result, List<PoisNav> points) {
            onNavDirectionsAboart();

            // set the navigation building and new points
            userData.setNavBuilding(b);
            userData.setNavPois(points);

            // handle drawing of the points
            handlePathDrawing(points);
        }

        @Override
        public void onNavRouteErrorOrCancel(String result) {
            onNavDirectionsAboart();
            // display the error cause
            Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
        }

        public void onNavDirectionsAboart() {
            status.task2 = true;
            if (status.task1 && status.task2)
                dialog.dismiss();
            else {
                // First task executed calls this
                clearLastNavigationInfo();
            }
        }
    }, this, id, (pos == null) ? entrancef : pos, floor);

    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            async1f.cancel(true);
            async2f.cancel(true);
        }
    });
    dialog.show();
    async1f.execute();
    async2f.execute();
}

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 w w .j a v a  2  s.co  m
    // 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//from ww w.j  a va 2s  .  c  o m
    // 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 av  a2  s . co 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();/*from  w  w  w. j a va 2 s  .  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;
            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 .jav  a  2  s  .  c om
        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  a  va 2s . 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//from w  w w.  j av a 2s . com
        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();
}