Example usage for android.app ProgressDialog dismiss

List of usage examples for android.app ProgressDialog dismiss

Introduction

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

Prototype

@Override
public void dismiss() 

Source Link

Document

Dismiss this dialog, removing it from the screen.

Usage

From source file:com.mobicage.rogerthat.plugins.messaging.widgets.PhotoUploadWidget.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == Crop.REQUEST_CROP) {
        handleCrop(resultCode, data);//from w ww.j  a  v a  2s .  c  om
    } else if (requestCode == PICK_IMAGE) {
        if (resultCode == Activity.RESULT_OK) {
            if (data != null && data.getData() != null) {
                if (mRatio == null) {
                    final Uri selectedImage = data.getData();

                    final ProgressDialog progressDialog = new ProgressDialog(mActivity);
                    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    progressDialog.setMessage(mActivity.getString(R.string.processing));
                    progressDialog.setCancelable(false);
                    progressDialog.show();

                    new SafeAsyncTask<Object, Object, Boolean>() {
                        @Override
                        protected Boolean safeDoInBackground(Object... params) {
                            L.d("Processing picture: " + selectedImage.getPath());
                            try {
                                File tmpUploadFile = getTmpUploadPhotoLocation();
                                if (tmpUploadFile.getAbsolutePath().equals(selectedImage.getPath())) {
                                    return true;
                                } else {
                                    InputStream is = mActivity.getContentResolver()
                                            .openInputStream(selectedImage);
                                    if (is != null) {
                                        try {
                                            OutputStream out = new FileOutputStream(tmpUploadFile);
                                            try {
                                                IOUtils.copy(is, out, 1024);
                                            } finally {
                                                out.close();
                                            }
                                        } finally {
                                            is.close();
                                        }
                                        return true;
                                    }
                                }
                            } catch (FileNotFoundException e) {
                                L.d(e);
                            } catch (Exception e) {
                                L.bug("Unknown exception occured while processing picture: "
                                        + selectedImage.toString(), e);
                            }

                            return false;
                        };

                        @Override
                        protected void safeOnPostExecute(Boolean result) {
                            progressDialog.dismiss();
                            if (result) {
                                handleSelection();
                            } else {
                                UIUtils.showLongToast(getContext(), R.string.crop__pick_error);
                            }
                        }

                        @Override
                        protected void safeOnCancelled(Boolean result) {
                        }

                        @Override
                        protected void safeOnProgressUpdate(Object... values) {
                        }

                        @Override
                        protected void safeOnPreExecute() {
                        };
                    }.execute();

                } else {
                    beginCrop(data.getData());
                    return;
                }
            } else {
                if (mRatio == null) {
                    handleSelection();
                } else {
                    beginCrop(mUriSavedImage);
                }
            }
        }
    } else {
        L.bug("Unexpected request code in onActivityResult: " + requestCode);
    }
}

From source file:com.xperia64.timidityae.TimidityActivity.java

public void saveCfgPart2(final String finalval, final String needToRename) {
    Intent new_intent = new Intent();
    new_intent.setAction(getResources().getString(R.string.msrv_rec));
    new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 16);
    new_intent.putExtra(getResources().getString(R.string.msrv_outfile), finalval);
    sendBroadcast(new_intent);
    final ProgressDialog prog;
    prog = new ProgressDialog(TimidityActivity.this);
    prog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
        @Override// w w w  .  ja v  a 2  s. c om
        public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
        }
    });
    prog.setTitle("Saving CFG");
    prog.setMessage("Saving...");
    prog.setIndeterminate(true);
    prog.setCancelable(false);
    prog.show();
    new Thread(new Runnable() {
        @Override
        public void run() {
            while (!localfinished && prog.isShowing()) {
                try {

                    Thread.sleep(25);
                } catch (InterruptedException e) {
                }
            }

            TimidityActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    String trueName = finalval;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null
                            && needToRename != null) {
                        if (Globals.renameDocumentFile(TimidityActivity.this, finalval, needToRename)) {
                            trueName = needToRename;
                        } else {
                            trueName = "Error";
                        }
                    }
                    Toast.makeText(TimidityActivity.this, "Wrote " + trueName, Toast.LENGTH_SHORT).show();
                    prog.dismiss();
                    fileFrag.getDir(fileFrag.currPath);
                }
            });

        }
    }).start();
}

From source file:com.mobicage.rogerthat.util.ui.SendMessageView.java

private void copyImageFile(final Uri selectedImage) {
    final ContentResolver cr = mActivity.getContentResolver();
    final ProgressDialog progressDialog = showProcessing();

    new SafeAsyncTask<Object, Object, Boolean>() {
        @Override//from w w w  . j  a v  a 2  s  . co  m
        protected Boolean safeDoInBackground(Object... params) {
            L.d("Processing picture: " + selectedImage.toString());

            try {
                String fileType = cr.getType(selectedImage);
                L.d("fileType: " + fileType);
                if (fileType == null || AttachmentViewerActivity.CONTENT_TYPE_JPEG.equalsIgnoreCase(fileType)) {
                    mUploadFileExtenstion = AttachmentViewerActivity.CONTENT_TYPE_JPEG;
                } else {
                    mUploadFileExtenstion = AttachmentViewerActivity.CONTENT_TYPE_JPEG;
                }

                if (mTmpUploadFile.getAbsolutePath().equals(selectedImage.getPath())) {
                    return true;
                } else {
                    InputStream is = cr.openInputStream(selectedImage);
                    if (is != null) {
                        try {
                            OutputStream out = new FileOutputStream(mTmpUploadFile);
                            try {
                                IOUtils.copy(is, out, 1024);
                            } finally {
                                out.close();
                            }
                        } finally {
                            is.close();
                        }
                        return true;
                    }
                }

            } catch (FileNotFoundException e) {
                L.d(e);
            } catch (Exception e) {
                L.bug("Unknown exception occured while processing picture: " + selectedImage.toString(), e);
            }

            return false;
        };

        @Override
        protected void safeOnPostExecute(Boolean result) {
            progressDialog.dismiss();
            if (result) {
                setPictureSelected();
            } else {
                UIUtils.showLongToast(mActivity, mActivity.getString(R.string.error_please_try_again));
            }
        }

        @Override
        protected void safeOnCancelled(Boolean result) {
        }

        @Override
        protected void safeOnProgressUpdate(Object... values) {
        }

        @Override
        protected void safeOnPreExecute() {
        };
    }.execute();
}

From source file:com.waz.zclient.pages.main.conversation.ConversationFragment.java

private void forwardMessage(final Message message) {
    getControllerFactory().getTrackingController()
            .tagEvent(new ForwardedMessageEvent(message.getMessageType().name()));

    final ShareCompat.IntentBuilder intentBuilder = ShareCompat.IntentBuilder.from(getActivity());
    intentBuilder.setChooserTitle(R.string.conversation__action_mode__fwd__chooser__title);
    switch (message.getMessageType()) {
    case TEXT:/*from  w w  w. j a  v  a2  s.  com*/
    case RICH_MEDIA:
        intentBuilder.setType("text/plain");
        intentBuilder.setText(message.getBody());
        intentBuilder.startChooser();
        break;
    case ANY_ASSET:
    case VIDEO_ASSET:
    case AUDIO_ASSET:
    case ASSET:
        final ProgressDialog dialog = ProgressDialog.show(getContext(),
                getString(R.string.conversation__action_mode__fwd__dialog__title),
                getString(R.string.conversation__action_mode__fwd__dialog__message), true, true, null);
        // TODO: Once https://wearezeta.atlassian.net/browse/CM-976 is resolved, this 'if' block can be removed
        if (message.getMessageType() == Message.Type.ASSET) {
            final ImageAsset imageAsset = message.getImage();
            intentBuilder.setType(imageAsset.getMimeType());
            imageAsset.saveImageToGallery(new ImageAsset.SaveCallback() {
                @Override
                public void imageSaved(Uri uri) {
                    if (getActivity() == null) {
                        return;
                    }
                    dialog.dismiss();
                    intentBuilder.addStream(uri);
                    intentBuilder.startChooser();
                }

                @Override
                public void imageSavingFailed(Exception ex) {
                    if (getActivity() == null) {
                        return;
                    }
                    dialog.dismiss();
                }
            });
        } else {
            final Asset messageAsset = message.getAsset();
            intentBuilder.setType(messageAsset.getMimeType());
            messageAsset.getContentUri(new Asset.LoadCallback<Uri>() {
                @Override
                public void onLoaded(Uri uri) {
                    if (getActivity() == null) {
                        return;
                    }
                    dialog.dismiss();
                    intentBuilder.addStream(uri);
                    intentBuilder.startChooser();
                }

                @Override
                public void onLoadFailed() {
                    if (getActivity() == null) {
                        return;
                    }
                    dialog.dismiss();
                }
            });
        }
        break;
    }
}

From source file:com.waz.zclient.pages.main.conversation.ConversationFragment.java

private void saveMessage(Message message) {
    if (message.getMessageType() == Message.Type.ASSET) {
        imageAssetToSave = message.getImage();
        if (PermissionUtils.hasSelfPermissions(getActivity(), SAVE_IMAGE_PERMISSIONS)) {
            saveImageAssetToGallery();//from   w  ww . j av  a  2 s . co m
        } else {
            ActivityCompat.requestPermissions(getActivity(), SAVE_IMAGE_PERMISSIONS,
                    SAVE_IMAGE_PERMISSION_REQUEST_ID);
        }
    } else {
        final ProgressDialog dialog = ProgressDialog.show(getContext(),
                getString(R.string.conversation__action_mode__fwd__dialog__title),
                getString(R.string.conversation__action_mode__fwd__dialog__message), true, true, null);
        final Asset asset = message.getAsset();
        asset.saveToDownloads(new Asset.LoadCallback() {

            @Override
            public void onLoaded(Object o) {
                if (getActivity() == null || getControllerFactory() == null
                        || getControllerFactory().isTornDown()) {
                    return;
                }
                getControllerFactory().getTrackingController()
                        .tagEvent(new SavedFileEvent(asset.getMimeType(), (int) asset.getSizeInBytes()));
                Toast.makeText(getActivity(), com.waz.zclient.ui.R.string.content__file__action__save_completed,
                        Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }

            @Override
            public void onLoadFailed() {
                if (getActivity() == null || getControllerFactory() == null
                        || getControllerFactory().isTornDown()) {
                    return;
                }
                Toast.makeText(getActivity(), com.waz.zclient.ui.R.string.content__file__action__save_error,
                        Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
    }
}

From source file:com.koushikdutta.superuser.MainActivity.java

void doRecoveryInstall() {
    final ProgressDialog dlg = new ProgressDialog(this);
    dlg.setTitle(R.string.installing);//w  ww .  j a  v a2 s .co m
    dlg.setMessage(getString(R.string.installing_superuser));
    dlg.setIndeterminate(true);
    dlg.show();
    new Thread() {
        void doEntry(ZipOutputStream zout, String entryName, String dest) throws IOException {
            ZipFile zf = new ZipFile(getPackageCodePath());
            ZipEntry ze = zf.getEntry(entryName);
            zout.putNextEntry(new ZipEntry(dest));
            InputStream in;
            StreamUtility.copyStream(in = zf.getInputStream(ze), zout);
            zout.closeEntry();
            in.close();
            zf.close();
        }

        public void run() {
            try {
                File zip = getFileStreamPath("superuser.zip");
                ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zip));
                doEntry(zout, "assets/update-binary", "META-INF/com/google/android/update-binary");
                doEntry(zout, "assets/install-recovery.sh", "install-recovery.sh");
                zout.close();

                ZipFile zf = new ZipFile(getPackageCodePath());
                ZipEntry ze = zf.getEntry("assets/" + getArch() + "/reboot");
                InputStream in;
                FileOutputStream reboot;
                StreamUtility.copyStream(in = zf.getInputStream(ze),
                        reboot = openFileOutput("reboot", MODE_PRIVATE));
                reboot.close();
                in.close();

                final File su = extractSu();

                String command = String.format("cat %s > /cache/superuser.zip\n", zip.getAbsolutePath())
                        + String.format("cat %s > /cache/su\n", su.getAbsolutePath())
                        + String.format("cat %s > /cache/Superuser.apk\n", getPackageCodePath())
                        + "mkdir /cache/recovery\n"
                        + "echo '--update_package=CACHE:superuser.zip' > /cache/recovery/command\n"
                        + "chmod 644 /cache/superuser.zip\n" + "chmod 644 /cache/recovery/command\n" + "sync\n"
                        + String.format("chmod 755 %s\n", getFileStreamPath("reboot").getAbsolutePath())
                        + "reboot recovery\n";
                Process p = Runtime.getRuntime().exec("su");
                p.getOutputStream().write(command.getBytes());
                p.getOutputStream().close();
                File rebootScript = getFileStreamPath("reboot.sh");
                StreamUtility.writeFile(rebootScript,
                        "reboot recovery ; " + getFileStreamPath("reboot").getAbsolutePath() + " recovery ;");
                p.waitFor();
                Runtime.getRuntime().exec(new String[] { "su", "-c", ". " + rebootScript.getAbsolutePath() });
                if (p.waitFor() != 0)
                    throw new Exception("non zero result");
            } catch (Exception ex) {
                ex.printStackTrace();
                dlg.dismiss();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setPositiveButton(android.R.string.ok, null);
                        builder.setTitle(R.string.install);
                        builder.setMessage(R.string.install_error);
                        builder.create().show();
                    }
                });
            }
        }
    }.start();
}

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/*from w w w.j  a  v  a 2 s.com*/
        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.aibasis.parent.ui.entrance.RegisterActivity.java

/**
 * /*from w  ww  . ja  v  a  2  s  . co m*/
 * 
 * @param view
 */
public void register(View view) {
    final String username = userNameEditText.getText().toString().trim();
    final String pwd = passwordEditText.getText().toString().trim();
    String confirm_pwd = confirmPwdEditText.getText().toString().trim();
    if (TextUtils.isEmpty(username)) {
        Toast.makeText(this, getResources().getString(R.string.User_name_cannot_be_empty), Toast.LENGTH_SHORT)
                .show();
        userNameEditText.requestFocus();
        return;
    } else if (TextUtils.isEmpty(pwd)) {
        Toast.makeText(this, getResources().getString(R.string.Password_cannot_be_empty), Toast.LENGTH_SHORT)
                .show();
        passwordEditText.requestFocus();
        return;
    } else if (TextUtils.isEmpty(confirm_pwd)) {
        Toast.makeText(this, getResources().getString(R.string.Confirm_password_cannot_be_empty),
                Toast.LENGTH_SHORT).show();
        confirmPwdEditText.requestFocus();
        return;
    } else if (!pwd.equals(confirm_pwd)) {
        Toast.makeText(this, getResources().getString(R.string.Two_input_password), Toast.LENGTH_SHORT).show();
        return;
    }

    if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setMessage(getResources().getString(R.string.Is_the_registered));
        pd.show();

        new Thread(new Runnable() {
            public void run() {
                //               try {
                //                  // sdk
                //                  EMChatManager.getInstance().createAccountOnServer(username, pwd);
                //                  runOnUiThread(new Runnable() {
                //                     public void run() {
                //                        if (!RegisterActivity.this.isFinishing())
                //                           pd.dismiss();
                //                        // ???
                //                        DemoApplication.getInstance().setUserName(username);
                //                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), 0).show();
                //                        finish();
                //                     }
                //                  });
                //               } catch (final EaseMobException e) {
                //                  runOnUiThread(new Runnable() {
                //                     public void run() {
                //                        if (!RegisterActivity.this.isFinishing())
                //                           pd.dismiss();
                //                        int errorCode=e.getErrorCode();
                //                        if(errorCode==EMError.NONETWORK_ERROR){
                //                           Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
                //                        }else if(errorCode == EMError.USER_ALREADY_EXISTS){
                //                           Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
                //                        }else if(errorCode == EMError.UNAUTHORIZED){
                //                           Toast.makeText(getApplicationContext(), getResources().getString(R.string.registration_failed_without_permission), Toast.LENGTH_SHORT).show();
                //                        }else if(errorCode == EMError.ILLEGAL_USER_NAME){
                //                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name),Toast.LENGTH_SHORT).show();
                //                        }else{
                //                           Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registration_failed) + e.getMessage(), Toast.LENGTH_SHORT).show();
                //                        }
                //                     }
                //                  });
                //               }
                accountAPI.register(username, pwd, new RequestListener() {
                    @Override
                    public void onComplete(String result) {
                        if (!RegisterActivity.this.isFinishing())
                            pd.dismiss();
                        try {
                            RegisterResult registerResult = RegisterResult.parse(result);
                            if (RegisterResult.SUCCESS.equals(registerResult.getResult())) {
                                DemoApplication.getInstance().setParentId(registerResult.getParentId());
                                DemoApplication.getInstance().setEaseId(registerResult.getEaseId());
                                DemoApplication.getInstance().setEasePassword(registerResult.getEasePassword());

                                SharePreferenceUtil sharePreferenceUtil = new SharePreferenceUtil(
                                        RegisterActivity.this);
                                sharePreferenceUtil.setParentId(registerResult.getParentId());
                            } else if (RegisterResult.USERNAME_EXISTS.equals(registerResult.getResult())) {
                                Toast.makeText(RegisterActivity.this,
                                        getResources().getString(R.string.User_already_exists),
                                        Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        finish();
                    }

                    @Override
                    public void onAPIException(APIException exception) {
                        Log.e("jijun", exception.toString());
                    }
                });

            }
        }).start();
    }
}

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// w w  w .jav  a2  s. 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(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();
}