Example usage for android.app ProgressDialog setMessage

List of usage examples for android.app ProgressDialog setMessage

Introduction

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

Prototype

@Override
    public void setMessage(CharSequence message) 

Source Link

Usage

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

public void performSearch(String query) {

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

    final ProgressDialog searchProgress = new ProgressDialog(context);
    searchProgress.setOwnerActivity(getActivity());
    searchProgress.setCancelable(true);//w  w w.  jav  a 2 s .co m
    searchProgress.setMax(100);
    searchProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

    final int[] counter = { 0 }; //Yes, this is essentially a pointer to an int :P

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

    task.setOnPreExecute(() -> {

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

    });

    task.setOnProgressUpdate((values) -> {

        if (isAdded()) {

            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) {
                counter[0] = counter[0] + 1;
                String update = String.format(getString(R.string.search_hits), counter[0]);
                searchProgress.setMessage(update);
            }

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

    task.setOnCancelled((result) -> {
        if (isAdded()) {
            Toast.makeText(context, R.string.search_cancelled, Toast.LENGTH_LONG).show();
        }
    });

    task.setOnPostExecute((result) -> {
        searchProgress.dismiss();

        if (!task.isCancelled() && isAdded()) {

            List<SearchResult> resultList = result.getOrElse(new ArrayList<>());

            if (resultList.size() > 0) {
                searchResults = resultList;
                showSearchResultDialog(resultList);
            } else {
                Toast.makeText(context, R.string.search_no_matches, Toast.LENGTH_LONG).show();
            }
        }
    });

    searchProgress.setOnCancelListener(dialog -> task.cancel(true));
    executeTask(task, query);
}

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);/*from   w  ww. j ava2 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;
                    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 ava  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;
                    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.andrewshu.android.reddit.threads.ThreadsListActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog;/*w  w w .j a  v a2  s.co  m*/
    ProgressDialog pdialog;
    AlertDialog.Builder builder;

    switch (id) {
    case Constants.DIALOG_LOGIN:
        dialog = new LoginDialog(this, mSettings, false) {
            public void onLoginChosen(String user, String password) {
                removeDialog(Constants.DIALOG_LOGIN);
                new MyLoginTask(user, password).execute();
            }
        };
        break;

    case Constants.DIALOG_THREAD_CLICK:
        dialog = new ThreadClickDialog(this, mSettings);
        break;

    case Constants.DIALOG_SORT_BY:
        builder = new AlertDialog.Builder(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
        builder.setTitle("Sort by:");
        builder.setSingleChoiceItems(Constants.ThreadsSort.SORT_BY_CHOICES, getSelectedSortBy(),
                sortByOnClickListener);
        dialog = builder.create();
        break;
    case Constants.DIALOG_SORT_BY_NEW:
        builder = new AlertDialog.Builder(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
        builder.setTitle("what's new");
        builder.setSingleChoiceItems(Constants.ThreadsSort.SORT_BY_NEW_CHOICES, getSelectedSortByNew(),
                sortByNewOnClickListener);
        dialog = builder.create();
        break;
    case Constants.DIALOG_SORT_BY_CONTROVERSIAL:
        builder = new AlertDialog.Builder(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
        builder.setTitle("most controversial");
        builder.setSingleChoiceItems(Constants.ThreadsSort.SORT_BY_CONTROVERSIAL_CHOICES,
                getSelectedSortByControversial(), sortByControversialOnClickListener);
        dialog = builder.create();
        break;
    case Constants.DIALOG_SORT_BY_TOP:
        builder = new AlertDialog.Builder(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
        builder.setTitle("top scoring");
        builder.setSingleChoiceItems(Constants.ThreadsSort.SORT_BY_TOP_CHOICES, getSelectedSortByTop(),
                sortByTopOnClickListener);
        dialog = builder.create();
        break;

    // "Please wait"
    case Constants.DIALOG_LOGGING_IN:
        pdialog = new ProgressDialog(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
        pdialog.setMessage("Logging in...");
        pdialog.setIndeterminate(true);
        pdialog.setCancelable(true);
        dialog = pdialog;
        break;

    default:
        throw new IllegalArgumentException("Unexpected dialog id " + id);
    }
    return dialog;
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

private void runReport(final DeletePostModel reportPostModel) {
    final EditText inputField = new EditText(activity);
    inputField.setSingleLine();//from w  w  w.j a  va  2  s  .c  om
    if (presentationModel.source.boardModel.allowReport != BoardModel.REPORT_WITH_COMMENT) {
        inputField.setEnabled(false);
        inputField.setKeyListener(null);
    } else {
        inputField.setText(reportPostModel.reportReason == null ? "" : reportPostModel.reportReason);
    }

    DialogInterface.OnClickListener dlgOnClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            if (currentTask != null)
                currentTask.cancel();
            if (pullableLayout.isRefreshing())
                setPullableNoRefreshing();
            reportPostModel.reportReason = inputField.getText().toString();
            final ProgressDialog progressDlg = new ProgressDialog(activity);
            final CancellableTask reportTask = new CancellableTask.BaseCancellableTask();
            progressDlg.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    reportTask.cancel();
                }
            });
            progressDlg.setCanceledOnTouchOutside(false);
            progressDlg.setMessage(resources.getString(R.string.dialog_report_progress));
            progressDlg.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    String error = null;
                    String targetUrl = null;
                    if (reportTask.isCancelled())
                        return;
                    try {
                        targetUrl = chan.reportPost(reportPostModel, null, reportTask);
                    } catch (Exception e) {
                        if (e instanceof InteractiveException) {
                            if (reportTask.isCancelled())
                                return;
                            ((InteractiveException) e).handle(activity, reportTask,
                                    new InteractiveException.Callback() {
                                        @Override
                                        public void onSuccess() {
                                            if (!reportTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                onClick(dialog, which);
                                            }
                                        }

                                        @Override
                                        public void onError(String message) {
                                            if (!reportTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
                                                runReport(reportPostModel);
                                            }
                                        }
                                    });
                            return;
                        }

                        Logger.e(TAG, "cannot report post", e);
                        error = e.getMessage() == null ? "" : e.getMessage();
                    }
                    if (reportTask.isCancelled())
                        return;
                    final boolean success = error == null;
                    final String result = success ? targetUrl : error;
                    Async.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (reportTask.isCancelled())
                                return;
                            progressDlg.dismiss();
                            if (success) {
                                if (result == null) {
                                    update();
                                } else {
                                    UrlHandler.open(result, activity);
                                }
                            } else {
                                Toast.makeText(activity,
                                        TextUtils.isEmpty(result) ? resources.getString(R.string.error_unknown)
                                                : result,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            });
        }
    };
    new AlertDialog.Builder(activity).setTitle(R.string.dialog_report_reason).setView(inputField)
            .setPositiveButton(R.string.dialog_report_button, dlgOnClick)
            .setNegativeButton(android.R.string.cancel, null).create().show();
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

@SuppressLint("InflateParams")
private void runDelete(final DeletePostModel deletePostModel, final boolean hasFiles) {
    Context dialogContext = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
            ? new ContextThemeWrapper(activity, R.style.Theme_Neutron)
            : activity;//  www .  j av a2s .com
    View dlgLayout = LayoutInflater.from(dialogContext).inflate(R.layout.dialog_delete, null);
    final EditText inputField = (EditText) dlgLayout.findViewById(R.id.dialog_delete_password_field);
    final CheckBox onlyFiles = (CheckBox) dlgLayout.findViewById(R.id.dialog_delete_only_files);
    inputField.setText(chan.getDefaultPassword());

    if (!presentationModel.source.boardModel.allowDeletePosts
            && !presentationModel.source.boardModel.allowDeleteFiles) {
        Logger.e(TAG, "board model doesn't support deleting");
        return;
    } else if (!presentationModel.source.boardModel.allowDeletePosts) {
        onlyFiles.setEnabled(false);
        onlyFiles.setChecked(true);
    } else if (presentationModel.source.boardModel.allowDeleteFiles && hasFiles) {
        onlyFiles.setEnabled(true);
    } else {
        onlyFiles.setEnabled(false);
    }

    DialogInterface.OnClickListener dlgOnClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            if (currentTask != null)
                currentTask.cancel();
            if (pullableLayout.isRefreshing())
                setPullableNoRefreshing();
            deletePostModel.onlyFiles = onlyFiles.isChecked();
            deletePostModel.password = inputField.getText().toString();
            final ProgressDialog progressDlg = new ProgressDialog(activity);
            final CancellableTask deleteTask = new CancellableTask.BaseCancellableTask();
            progressDlg.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    deleteTask.cancel();
                }
            });
            progressDlg.setCanceledOnTouchOutside(false);
            progressDlg.setMessage(resources.getString(R.string.dialog_delete_progress));
            progressDlg.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    String error = null;
                    String targetUrl = null;
                    if (deleteTask.isCancelled())
                        return;
                    try {
                        targetUrl = chan.deletePost(deletePostModel, null, deleteTask);
                    } catch (Exception e) {
                        if (e instanceof InteractiveException) {
                            if (deleteTask.isCancelled())
                                return;
                            ((InteractiveException) e).handle(activity, deleteTask,
                                    new InteractiveException.Callback() {
                                        @Override
                                        public void onSuccess() {
                                            if (!deleteTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                onClick(dialog, which);
                                            }
                                        }

                                        @Override
                                        public void onError(String message) {
                                            if (!deleteTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
                                                runDelete(deletePostModel, hasFiles);
                                            }
                                        }
                                    });
                            return;
                        }

                        Logger.e(TAG, "cannot delete post", e);
                        error = e.getMessage() == null ? "" : e.getMessage();
                    }
                    if (deleteTask.isCancelled())
                        return;
                    final boolean success = error == null;
                    final String result = success ? targetUrl : error;
                    Async.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (deleteTask.isCancelled())
                                return;
                            progressDlg.dismiss();
                            if (success) {
                                if (result == null) {
                                    update();
                                } else {
                                    UrlHandler.open(result, activity);
                                }
                            } else {
                                Toast.makeText(activity,
                                        TextUtils.isEmpty(result) ? resources.getString(R.string.error_unknown)
                                                : result,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            });
        }
    };
    new AlertDialog.Builder(activity).setTitle(R.string.dialog_delete_password).setView(dlgLayout)
            .setPositiveButton(R.string.dialog_delete_button, dlgOnClick)
            .setNegativeButton(android.R.string.cancel, null).create().show();
}

From source file:com.andrewshu.android.reddit.user.ProfileActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog;/*from   w  ww .j  a  va2s. c o m*/
    ProgressDialog pdialog;
    AlertDialog.Builder builder;
    LayoutInflater inflater;
    View layout; // used for inflated views for AlertDialog.Builder.setView()

    switch (id) {
    case Constants.DIALOG_LOGIN:
        dialog = new LoginDialog(this, mSettings, false) {
            @Override
            public void onLoginChosen(String user, String password) {
                removeDialog(Constants.DIALOG_LOGIN);
                new MyLoginTask(user, password).execute();
            }
        };
        break;

    case Constants.DIALOG_COMPOSE:
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        builder = new AlertDialog.Builder(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
        layout = inflater.inflate(R.layout.compose_dialog, null);

        Common.setTextColorFromTheme(mSettings.getTheme(), getResources(),
                (TextView) layout.findViewById(R.id.compose_destination_textview),
                (TextView) layout.findViewById(R.id.compose_subject_textview),
                (TextView) layout.findViewById(R.id.compose_message_textview),
                (TextView) layout.findViewById(R.id.compose_captcha_textview),
                (TextView) layout.findViewById(R.id.compose_captcha_loading));

        final EditText composeDestination = (EditText) layout.findViewById(R.id.compose_destination_input);
        final EditText composeSubject = (EditText) layout.findViewById(R.id.compose_subject_input);
        final EditText composeText = (EditText) layout.findViewById(R.id.compose_text_input);
        final Button composeSendButton = (Button) layout.findViewById(R.id.compose_send_button);
        final Button composeCancelButton = (Button) layout.findViewById(R.id.compose_cancel_button);
        final EditText composeCaptcha = (EditText) layout.findViewById(R.id.compose_captcha_input);
        composeDestination.setText(mUsername);

        dialog = builder.setView(layout).create();
        final Dialog composeDialog = dialog;
        composeSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                ThingInfo hi = new ThingInfo();

                if (!FormValidation.validateComposeMessageInputFields(ProfileActivity.this, composeDestination,
                        composeSubject, composeText, composeCaptcha))
                    return;

                hi.setDest(composeDestination.getText().toString().trim());
                hi.setSubject(composeSubject.getText().toString().trim());
                new MyMessageComposeTask(composeDialog, hi, composeCaptcha.getText().toString().trim())
                        .execute(composeText.getText().toString().trim());
                removeDialog(Constants.DIALOG_COMPOSE);
            }
        });
        composeCancelButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                removeDialog(Constants.DIALOG_COMPOSE);
            }
        });
        break;

    case Constants.DIALOG_THREAD_CLICK:
        dialog = new ThreadClickDialog(this, mSettings);
        break;

    // "Please wait"
    case Constants.DIALOG_LOGGING_IN:
        pdialog = new ProgressDialog(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
        pdialog.setMessage("Logging in...");
        pdialog.setIndeterminate(true);
        pdialog.setCancelable(true);
        dialog = pdialog;
        break;
    case Constants.DIALOG_REPLYING:
        pdialog = new ProgressDialog(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
        pdialog.setMessage("Sending reply...");
        pdialog.setIndeterminate(true);
        pdialog.setCancelable(true);
        dialog = pdialog;
        break;
    case Constants.DIALOG_COMPOSING:
        pdialog = new ProgressDialog(new ContextThemeWrapper(this, mSettings.getDialogTheme()));
        pdialog.setMessage("Composing message...");
        pdialog.setIndeterminate(true);
        pdialog.setCancelable(true);
        dialog = pdialog;
        break;

    default:
        throw new IllegalArgumentException("Unexpected dialog id " + id);
    }
    return dialog;
}

From source file:com.android.mms.ui.ComposeMessageActivity.java

private void processPickResult(final Intent data) {
    // The EXTRA_PHONE_URIS stores the phone's urls that were selected by user in the
    // multiple phone picker.
    final Parcelable[] uris = data.getParcelableArrayExtra(Intents.EXTRA_PHONE_URIS);

    final int recipientCount = uris != null ? uris.length : 0;

    final int recipientLimit = MmsConfig.getRecipientLimit();
    if (recipientLimit != Integer.MAX_VALUE && recipientCount > recipientLimit) {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.too_many_recipients, recipientCount, recipientLimit))
                .setPositiveButton(android.R.string.ok, null).create().show();
        return;/*from   w  w w.  ja  va2s . com*/
    }

    final Handler handler = new Handler();
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setTitle(getText(R.string.pick_too_many_recipients));
    progressDialog.setMessage(getText(R.string.adding_recipients));
    progressDialog.setIndeterminate(true);
    progressDialog.setCancelable(false);

    final Runnable showProgress = new Runnable() {
        @Override
        public void run() {
            progressDialog.show();
        }
    };
    // Only show the progress dialog if we can not finish off parsing the return data in 1s,
    // otherwise the dialog could flicker.
    handler.postDelayed(showProgress, 1000);

    new Thread(new Runnable() {
        @Override
        public void run() {
            final ContactList list;
            try {
                list = ContactList.blockingGetByUris(uris);
            } finally {
                handler.removeCallbacks(showProgress);
                progressDialog.dismiss();
            }
            // TODO: there is already code to update the contact header widget and recipients
            // editor if the contacts change. we can re-use that code.
            final Runnable populateWorker = new Runnable() {
                @Override
                public void run() {
                    mRecipientsEditor.populate(list);
                    updateTitle(list);
                }
            };
            handler.post(populateWorker);
        }
    }, "ComoseMessageActivity.processPickResult").start();
}

From source file:org.telegram.messenger.MessagesController.java

public void startSecretChat(final Context context, final TLRPC.User user) {
    if (user == null) {
        return;//from   w w w. ja  va 2  s . c  o  m
    }
    final ProgressDialog progressDialog = new ProgressDialog(context);
    progressDialog.setMessage(context.getString(R.string.Loading));
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.setCancelable(false);
    progressDialog.show();
    TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
    req.random_length = 256;
    req.version = MessagesStorage.lastSecretVersion;
    ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() {
        @Override
        public void run(TLObject response, TLRPC.TL_error error) {
            if (error == null) {
                TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response;
                if (response instanceof TLRPC.TL_messages_dhConfig) {
                    if (!Utilities.isGoodPrime(res.p, res.g)) {
                        Utilities.RunOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        progressDialog.dismiss();
                                    }
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                            }
                        });
                        return;
                    }
                    MessagesStorage.secretPBytes = res.p;
                    MessagesStorage.secretG = res.g;
                    MessagesStorage.lastSecretVersion = res.version;
                    MessagesStorage.Instance.saveSecretParams(MessagesStorage.lastSecretVersion,
                            MessagesStorage.secretG, MessagesStorage.secretPBytes);
                }
                final byte[] salt = new byte[256];
                for (int a = 0; a < 256; a++) {
                    salt[a] = (byte) ((byte) (random.nextDouble() * 256) ^ res.random[a]);
                }

                BigInteger i_g_a = BigInteger.valueOf(MessagesStorage.secretG);
                i_g_a = i_g_a.modPow(new BigInteger(1, salt), new BigInteger(1, MessagesStorage.secretPBytes));
                byte[] g_a = i_g_a.toByteArray();
                if (g_a.length > 256) {
                    byte[] correctedAuth = new byte[256];
                    System.arraycopy(g_a, 1, correctedAuth, 0, 256);
                    g_a = correctedAuth;
                }

                TLRPC.TL_messages_requestEncryption req2 = new TLRPC.TL_messages_requestEncryption();
                req2.g_a = g_a;
                req2.user_id = getInputUser(user);
                req2.random_id = (int) (random.nextDouble() * Integer.MAX_VALUE);
                ConnectionsManager.Instance.performRpc(req2, new RPCRequest.RPCRequestDelegate() {
                    @Override
                    public void run(final TLObject response, TLRPC.TL_error error) {
                        if (error == null) {
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        try {
                                            progressDialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                    }
                                    TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) response;
                                    chat.user_id = chat.participant_id;
                                    encryptedChats.put(chat.id, chat);
                                    chat.a_or_b = salt;
                                    TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
                                    dialog.id = ((long) chat.id) << 32;
                                    dialog.unread_count = 0;
                                    dialog.top_message = 0;
                                    dialog.last_message_date = ConnectionsManager.Instance.getCurrentTime();
                                    dialogs_dict.put(dialog.id, dialog);
                                    dialogs.add(dialog);
                                    dialogsServerOnly.clear();
                                    Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {
                                        @Override
                                        public int compare(TLRPC.TL_dialog tl_dialog,
                                                TLRPC.TL_dialog tl_dialog2) {
                                            if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {
                                                return 0;
                                            } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {
                                                return 1;
                                            } else {
                                                return -1;
                                            }
                                        }
                                    });
                                    for (TLRPC.TL_dialog d : dialogs) {
                                        if ((int) d.id != 0) {
                                            dialogsServerOnly.add(d);
                                        }
                                    }
                                    NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                                    MessagesStorage.Instance.putEncryptedChat(chat, user, dialog);
                                    NotificationCenter.Instance.postNotificationName(encryptedChatCreated,
                                            chat);
                                }
                            });
                        } else {
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        try {
                                            progressDialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                        builder.setTitle(context.getString(R.string.AppName));
                                        builder.setMessage(String.format(
                                                context.getString(R.string.CreateEncryptedChatOutdatedError),
                                                user.first_name, user.first_name));
                                        builder.setPositiveButton(
                                                ApplicationLoader.applicationContext.getString(R.string.OK),
                                                null);
                                        builder.show().setCanceledOnTouchOutside(true);
                                    }
                                }
                            });
                        }
                    }
                }, null, true,
                        RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
            } else {
                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!((ActionBarActivity) context).isFinishing()) {
                            try {
                                progressDialog.dismiss();
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                        }
                    }
                });
            }
        }
    }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
}

From source file:com.andrewshu.android.reddit.profile.ProfileActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog;/*from www  . j a v a 2  s.  c  o m*/
    ProgressDialog pdialog;
    AlertDialog.Builder builder;
    LayoutInflater inflater;
    View layout; // used for inflated views for AlertDialog.Builder.setView()

    switch (id) {
    case Constants.DIALOG_LOGIN:
        dialog = new LoginDialog(this, mSettings, false) {
            @Override
            public void onLoginChosen(String user, String password) {
                dismissDialog(Constants.DIALOG_LOGIN);
                new MyLoginTask(user, password).execute();
            }
        };
        break;

    case Constants.DIALOG_COMPOSE:
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        builder = new AlertDialog.Builder(this);
        layout = inflater.inflate(R.layout.compose_dialog, null);
        final EditText composeDestination = (EditText) layout.findViewById(R.id.compose_destination_input);
        final EditText composeSubject = (EditText) layout.findViewById(R.id.compose_subject_input);
        final EditText composeText = (EditText) layout.findViewById(R.id.compose_text_input);
        final Button composeSendButton = (Button) layout.findViewById(R.id.compose_send_button);
        final Button composeCancelButton = (Button) layout.findViewById(R.id.compose_cancel_button);
        final EditText composeCaptcha = (EditText) layout.findViewById(R.id.compose_captcha_input);
        composeDestination.setText(mUsername);

        dialog = builder.setView(layout).create();
        final Dialog composeDialog = dialog;
        composeSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                ThingInfo hi = new ThingInfo();
                // reddit.com performs these sanity checks too.
                if ("".equals(composeDestination.getText().toString().trim())) {
                    Toast.makeText(ProfileActivity.this, "please enter a username", Toast.LENGTH_LONG).show();
                    return;
                }
                if ("".equals(composeSubject.getText().toString().trim())) {
                    Toast.makeText(ProfileActivity.this, "please enter a subject", Toast.LENGTH_LONG).show();
                    return;
                }
                if ("".equals(composeText.getText().toString().trim())) {
                    Toast.makeText(ProfileActivity.this, "you need to enter a message", Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                if (composeCaptcha.getVisibility() == View.VISIBLE
                        && "".equals(composeCaptcha.getText().toString().trim())) {
                    Toast.makeText(ProfileActivity.this, "", Toast.LENGTH_LONG).show();
                    return;
                }
                hi.setDest(composeDestination.getText().toString().trim());
                hi.setSubject(composeSubject.getText().toString().trim());
                new MyMessageComposeTask(composeDialog, hi, composeCaptcha.getText().toString().trim())
                        .execute(composeText.getText().toString().trim());
                dismissDialog(Constants.DIALOG_COMPOSE);
            }
        });
        composeCancelButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dismissDialog(Constants.DIALOG_COMPOSE);
            }
        });
        break;

    case Constants.DIALOG_THREAD_CLICK:
        inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        builder = new AlertDialog.Builder(this);
        dialog = builder.setView(inflater.inflate(R.layout.thread_click_dialog, null)).create();
        break;

    // "Please wait"
    case Constants.DIALOG_LOGGING_IN:
        pdialog = new ProgressDialog(this);
        pdialog.setMessage("Logging in...");
        pdialog.setIndeterminate(true);
        pdialog.setCancelable(false);
        dialog = pdialog;
        break;
    case Constants.DIALOG_REPLYING:
        pdialog = new ProgressDialog(this);
        pdialog.setMessage("Sending reply...");
        pdialog.setIndeterminate(true);
        pdialog.setCancelable(false);
        dialog = pdialog;
        break;
    case Constants.DIALOG_COMPOSING:
        pdialog = new ProgressDialog(this);
        pdialog.setMessage("Composing message...");
        pdialog.setIndeterminate(true);
        pdialog.setCancelable(false);
        dialog = pdialog;
        break;

    default:
        throw new IllegalArgumentException("Unexpected dialog id " + id);
    }
    return dialog;
}