Example usage for android.app AlertDialog show

List of usage examples for android.app AlertDialog show

Introduction

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

Prototype

public void show() 

Source Link

Document

Start the dialog and display it on screen.

Usage

From source file:com.otaupdater.utils.UserUtils.java

public static void showLoginDialog(final Context ctx, String defUsername, final DialogCallback dlgCallback,
        final LoginCallback loginCallback) {
    @SuppressLint("InflateParams")
    View view = LayoutInflater.from(ctx).inflate(R.layout.login_dialog, null);
    if (view == null)
        return;/*  w w  w .  java 2 s . com*/
    final EditText inputUsername = (EditText) view.findViewById(R.id.auth_username);
    final EditText inputPassword = (EditText) view.findViewById(R.id.auth_password);

    if (defUsername != null)
        inputUsername.setText(defUsername);

    AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
    builder.setTitle(R.string.alert_login_title);
    builder.setView(view);
    builder.setPositiveButton(R.string.login, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            /* set below */ }
    });
    builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            if (loginCallback != null)
                loginCallback.onCancel();
        }
    });

    final AlertDialog dlg = builder.create();
    dlg.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            if (dlgCallback != null)
                dlgCallback.onDialogShown(dlg);
            Button button = dlg.getButton(DialogInterface.BUTTON_POSITIVE);
            if (button == null)
                return;
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String username = inputUsername.getText().toString();
                    final String password = inputPassword.getText().toString();

                    if (username.length() == 0 || password.length() == 0) {
                        Toast.makeText(ctx, R.string.toast_blank_userpass_error, Toast.LENGTH_LONG).show();
                        return;
                    }

                    dlg.dismiss();

                    APIUtils.userLogin(ctx, username, password, new APIUtils.ProgressDialogAPICallback(ctx,
                            ctx.getString(R.string.alert_logging_in), dlgCallback) {
                        @Override
                        public void onSuccess(String message, JSONObject respObj) {
                            try {
                                String realUsername = respObj.getString("username");
                                String hmacKey = respObj.getString("key");
                                Config.getInstance(ctx).storeLogin(realUsername, hmacKey);
                                if (loginCallback != null)
                                    loginCallback.onLoggedIn(realUsername);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(String message, JSONObject respObj) {
                            //TODO show some error
                        }
                    });
                }
            });
        }
    });
    dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            if (dlgCallback != null)
                dlgCallback.onDialogClosed(dlg);
        }
    });
    dlg.show();
}

From source file:in.animeshpathak.nextbus.NextBusMain.java

/**
 * Creates the Application Info dialog with clickable links.
 * //from   w w  w  . ja va  2  s. c om
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
private void showVersionInfoDialog() throws UnsupportedEncodingException, IOException {
    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle(getString(R.string.app_name) + " " + getString(R.string.version_name));

    AssetManager assetManager = getResources().getAssets();
    String versionInfoFile = getString(R.string.versioninfo_asset);
    InputStreamReader reader = new InputStreamReader(assetManager.open(versionInfoFile), "UTF-8");
    BufferedReader br = new BufferedReader(reader);
    StringBuffer sbuf = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
        sbuf.append(line);
        sbuf.append("\r\n");
    }

    final ScrollView scroll = new ScrollView(this);
    final TextView message = new TextView(this);
    final SpannableString sWlinks = new SpannableString(sbuf.toString());
    Linkify.addLinks(sWlinks, Linkify.WEB_URLS);
    message.setText(sWlinks);
    message.setMovementMethod(LinkMovementMethod.getInstance());
    message.setPadding(15, 15, 15, 15);
    scroll.addView(message);
    alertDialog.setView(scroll);
    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // nothing to do, just dismiss dialog
        }
    });
    alertDialog.show();
}

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

public void onWindowFocusChanged(boolean bool) {
    super.onWindowFocusChanged(bool);
    Log.d("DEBUG", "onWindowFocusChanged");
    if (CreateExampleActivity.create_example_result != null) {
        synchronized (CreateExampleActivity.create_example_result) {
            final AlertDialog dialog = new AlertDialog.Builder(this).create();
            final boolean success = CreateExampleActivity.create_example_result.success();
            dialog.setTitle(CreateExampleActivity.create_example_result.getTitle());
            dialog.setMessage(CreateExampleActivity.create_example_result.getMessage());
            CreateExampleActivity.create_example_result = null;
            dialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // TODO avoid moving to item view if previous thread was
                    // interrupted? create_example.isInterrupted() but need
                    // user to be aware if we
                    // have created example already - progress dialog is set
                    // cancelable, so back button will work? maybe should
                    // avoid encouraging cancel
                    // on POST operations ... not sure what to do if no
                    // response from server - guess we will time out
                    // eventually ...
                    if (success) {
                        // want to go back to individual item screen now ...
                        ItemListActivity.loadItem(CreateExampleActivity.this, item_id);
                    }//from w w w . j  a  v a2  s.  c  om
                }
            });
            dialog.show();

        }
    }
}

From source file:cgeo.geocaching.cgeocaches.java

public void removeFromHistoryCheck() {
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setCancelable(true);//ww  w . j av a2  s . c  o  m
    dialog.setTitle(res.getString(R.string.caches_removing_from_history));
    dialog.setMessage((adapter != null && adapter.getCheckedCount() > 0)
            ? res.getString(R.string.cache_remove_from_history)
            : res.getString(R.string.cache_clear_history));
    dialog.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            removeFromHistory();
            dialog.cancel();
        }
    });
    dialog.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

    AlertDialog alert = dialog.create();
    alert.show();
}

From source file:cm.aptoide.pt.RemoteInTab.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case UPDATE_REPO:
        final AlertDialog upd_alrt = new AlertDialog.Builder(this).create();
        if (!db.areServers()) {
            upd_alrt.setIcon(android.R.drawable.ic_dialog_alert);
            upd_alrt.setTitle("Empty");
            upd_alrt.setMessage(/*from   w ww  .  j a v  a  2 s. c om*/
                    "There are no enabled repositories in your list.\nPlease add repository or enable the ones you have!");
            upd_alrt.setButton("Ok", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });
        } else {
            upd_alrt.setIcon(android.R.drawable.ic_dialog_alert);
            upd_alrt.setTitle("Update repositories");
            upd_alrt.setMessage(
                    "Do you wish to update repositories?\nThis can take a while (WiFi is advised)...");
            upd_alrt.setButton("Yes", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    updateRepos();
                }
            });
            upd_alrt.setButton2("No", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    upd_alrt.dismiss();
                }
            });
        }
        upd_alrt.show();
        return true;
    case MANAGE_REPO:
        Intent i = new Intent(this, ManageRepo.class);
        startActivityForResult(i, NEWREPO_FLAG);
        return true;
    case SEARCH_MENU:
        onSearchRequested();
        return true;
    case ABOUT:
        LayoutInflater li = LayoutInflater.from(this);
        View view = li.inflate(R.layout.about, null);
        Builder p = new AlertDialog.Builder(this).setView(view);
        final AlertDialog alrt = p.create();
        alrt.setIcon(R.drawable.icon);
        alrt.setTitle("APTOIDE");
        alrt.setButton("ChangeLog", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                Uri uri = Uri.parse("http://aptoide.com/changelog.html");
                startActivity(new Intent(Intent.ACTION_VIEW, uri));
            }
        });
        alrt.show();
        return true;
    case SETTINGS:
        Intent s = new Intent(RemoteInTab.this, Settings.class);
        s.putExtra("order", order_lst);
        startActivityForResult(s, SETTINGS_FLAG);
    }
    return super.onOptionsItemSelected(item);
}

From source file:biz.bokhorst.xprivacy.ActivityApp.java

private void optionKill(final int which) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this);
    alertDialogBuilder.setTitle(R.string.menu_app_kill);
    alertDialogBuilder.setMessage(R.string.msg_sure);
    alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
    alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
        @Override//from   w  w  w.j  a  v  a2  s  .  c om
        public void onClick(DialogInterface dialog, int _which) {
            XApplication.manage(ActivityApp.this, mAppInfo.getPackageName().get(which),
                    XApplication.cActionKillProcess);
            Toast.makeText(ActivityApp.this, getString(R.string.msg_done), Toast.LENGTH_LONG).show();
        }
    });
    alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

From source file:com.df.app.procedures.CarRecogniseLayout.java

/**
 * //from  ww w .j  a va2 s  .  com
 */
private void selectCarManually() {
    if (!mCarSettings.getBrandString().equals("")) {
        View view1 = ((Activity) rootView.getContext()).getLayoutInflater().inflate(R.layout.popup_layout,
                null);
        TableLayout contentArea = (TableLayout) view1.findViewById(R.id.contentArea);
        TextView content = new TextView(view1.getContext());
        content.setText(R.string.reMatch);
        content.setTextSize(20f);
        contentArea.addView(content);

        setTextView(view1, R.id.title, getResources().getString(R.string.alert));

        AlertDialog dialog = new AlertDialog.Builder(rootView.getContext()).setView(view1)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mHideContentCallback.hideContent();
                        showSelectCarDialog();
                    }
                }).setNegativeButton(R.string.cancel, null).create();

        dialog.show();
    } else {
        showSelectCarDialog();
    }
}

From source file:be.ppareit.swiftp.gui.PreferenceFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Resources resources = getResources();

    TwoStatePreference runningPref = findPref("running_switch");
    updateRunningState();/*from  w  w  w  .j av  a 2s . co  m*/
    runningPref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((Boolean) newValue) {
            startServer();
        } else {
            stopServer();
        }
        return true;
    });

    PreferenceScreen prefScreen = findPref("preference_screen");
    Preference marketVersionPref = findPref("market_version");
    marketVersionPref.setOnPreferenceClickListener(preference -> {
        // start the market at our application
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("market://details?id=be.ppareit.swiftp"));
        try {
            // this can fail if there is no market installed
            startActivity(intent);
        } catch (Exception e) {
            Cat.e("Failed to launch the market.");
            e.printStackTrace();
        }
        return false;
    });
    if (!App.isFreeVersion()) {
        prefScreen.removePreference(marketVersionPref);
    }

    updateLoginInfo();

    EditTextPreference usernamePref = findPref("username");
    usernamePref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newUsername = (String) newValue;
        if (preference.getSummary().equals(newUsername))
            return false;
        if (!newUsername.matches("[a-zA-Z0-9]+")) {
            Toast.makeText(getActivity(), R.string.username_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        stopServer();
        return true;
    });

    mPassWordPref = findPref("password");
    mPassWordPref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });
    mAutoconnectListPref = findPref("autoconnect_preference");
    mAutoconnectListPref.setOnPopulateListener(pref -> {
        Cat.d("autoconnect populate listener");

        WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        if (configs == null) {
            Cat.e("Unable to receive wifi configurations, bark at user and bail");
            Toast.makeText(getActivity(), R.string.autoconnect_error_enable_wifi_for_access_points,
                    Toast.LENGTH_LONG).show();
            return;
        }
        CharSequence[] ssids = new CharSequence[configs.size()];
        CharSequence[] niceSsids = new CharSequence[configs.size()];
        for (int i = 0; i < configs.size(); ++i) {
            ssids[i] = configs.get(i).SSID;
            String ssid = configs.get(i).SSID;
            if (ssid.length() > 2 && ssid.startsWith("\"") && ssid.endsWith("\"")) {
                ssid = ssid.substring(1, ssid.length() - 1);
            }
            niceSsids[i] = ssid;
        }
        pref.setEntries(niceSsids);
        pref.setEntryValues(ssids);
    });
    mAutoconnectListPref.setOnPreferenceClickListener(preference -> {
        Cat.d("Clicked");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    new AlertDialog.Builder(getContext()).setTitle(R.string.request_coarse_location_dlg_title)
                            .setMessage(R.string.request_coarse_location_dlg_message)
                            .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                                requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                                        ACCESS_COARSE_LOCATION_REQUEST_CODE);
                            }).setOnCancelListener(dialog -> {
                                mAutoconnectListPref.getDialog().cancel();
                            }).create().show();
                } else {
                    requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                            ACCESS_COARSE_LOCATION_REQUEST_CODE);
                }
            }
        }
        return false;
    });

    EditTextPreference portnum_pref = findPref("portNum");
    portnum_pref.setSummary(sp.getString("portNum", resources.getString(R.string.portnumber_default)));
    portnum_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newPortnumString = (String) newValue;
        if (preference.getSummary().equals(newPortnumString))
            return false;
        int portnum = 0;
        try {
            portnum = Integer.parseInt(newPortnumString);
        } catch (Exception e) {
            Cat.d("Error parsing port number! Moving on...");
        }
        if (portnum <= 0 || 65535 < portnum) {
            Toast.makeText(getActivity(), R.string.port_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        preference.setSummary(newPortnumString);
        stopServer();
        return true;
    });

    Preference chroot_pref = findPref("chrootDir");
    chroot_pref.setSummary(FsSettings.getChrootDirAsString());
    chroot_pref.setOnPreferenceClickListener(preference -> {
        AlertDialog folderPicker = new FolderPickerDialogBuilder(getActivity(), FsSettings.getChrootDir())
                .setSelectedButton(R.string.select, path -> {
                    if (preference.getSummary().equals(path))
                        return;
                    if (!FsSettings.setChrootDir(path))
                        return;
                    // TODO: this is a hotfix, create correct resources, improve UI/UX
                    final File root = new File(path);
                    if (!root.canRead()) {
                        Toast.makeText(getActivity(), "Notice that we can't read/write in this folder.",
                                Toast.LENGTH_LONG).show();
                    } else if (!root.canWrite()) {
                        Toast.makeText(getActivity(),
                                "Notice that we can't write in this folder, reading will work. Writing in sub folders might work.",
                                Toast.LENGTH_LONG).show();
                    }

                    preference.setSummary(path);
                    stopServer();
                }).setNegativeButton(R.string.cancel, null).create();
        folderPicker.show();
        return true;
    });

    final CheckBoxPreference wakelock_pref = findPref("stayAwake");
    wakelock_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });

    final CheckBoxPreference writeExternalStorage_pref = findPref("writeExternalStorage");
    String externalStorageUri = FsSettings.getExternalStorageUri();
    if (externalStorageUri == null) {
        writeExternalStorage_pref.setChecked(false);
    }
    writeExternalStorage_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((boolean) newValue) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, ACTION_OPEN_DOCUMENT_TREE);
            return false;
        } else {
            FsSettings.setExternalStorageUri(null);
            return true;
        }
    });

    ListPreference theme = findPref("theme");
    theme.setSummary(theme.getEntry());
    theme.setOnPreferenceChangeListener((preference, newValue) -> {
        theme.setSummary(theme.getEntry());
        getActivity().recreate();
        return true;
    });

    Preference help = findPref("help");
    help.setOnPreferenceClickListener(preference -> {
        Cat.v("On preference help clicked");
        Context context = getActivity();
        AlertDialog ad = new AlertDialog.Builder(context).setTitle(R.string.help_dlg_title)
                .setMessage(R.string.help_dlg_message).setPositiveButton(android.R.string.ok, null).create();
        ad.show();
        Linkify.addLinks((TextView) ad.findViewById(android.R.id.message), Linkify.ALL);
        return true;
    });

    Preference about = findPref("about");
    about.setOnPreferenceClickListener(preference -> {
        startActivity(new Intent(getActivity(), AboutActivity.class));
        return true;
    });

}

From source file:com.dwdesign.tweetings.activity.ComposeActivity.java

protected void send() {
    final String text_orig = mEditText != null ? parseString(mEditText.getText()) : null;
    final String atext = mIsPhotoAttached || mIsImageAttached
            ? mUploadUseExtension ? getImageUploadStatus(this, FAKE_IMAGE_LINK, text_orig)
                    : text_orig + " " + FAKE_IMAGE_LINK
            : text_orig;//from  ww  w. jav  a2 s .  co m
    final int count = mValidator.getTweetLength(atext);
    if (!isNullOrEmpty(mUploadProvider) && (mIsPhotoAttached || mIsImageAttached)) {
        postMedia();
    } else if (count > 140) {
        if (mScheduleDate != null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.schedule_tweet));
            builder.setMessage(getString(R.string.schedule_tweet_too_long));
            builder.setCancelable(true);
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.tweet_too_long));
            builder.setMessage(getString(R.string.confirm_twitlonger));
            builder.setCancelable(true);
            builder.setPositiveButton(getString(R.string.send_to_twitlonger),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            postTwitlonger();
                        }
                    });
            builder.setNeutralButton(getString(R.string.split_tweets), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    splitTweets();
                }
            });
            builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    //actuallyPost();
                }
            });
            //
            AlertDialog alert = builder.create();
            alert.show();
        }

    } else {
        if (mScheduleDate != null && isNullOrEmpty(mUploadProvider) && (mIsPhotoAttached || mIsImageAttached)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.schedule_tweet));
            builder.setMessage(getString(R.string.schedule_tweet_pic_twitter));
            builder.setCancelable(true);
            AlertDialog alert = builder.create();
            alert.show();
        } else if (mScheduleDate != null && mIsBuffer == true) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.schedule_tweet));
            builder.setMessage(getString(R.string.schedule_tweet_buffer));
            builder.setCancelable(true);
            AlertDialog alert = builder.create();
            alert.show();
        } else if (mIsBuffer == true && isNullOrEmpty(mUploadProvider)
                && (mIsPhotoAttached || mIsImageAttached)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.add_to_buffer));
            builder.setMessage(getString(R.string.buffer_pic_twitter));
            builder.setCancelable(true);
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            actuallyPost();
        }
    }
}

From source file:com.awrtechnologies.carbudgetsales.MainActivity.java

/**
 * Function to display simple Alert Dialog
 *
 * @param context - application context//from w w w .  j a  v a2  s .  c  o m
 * @param title   - alert dialog title
 * @param message - alert message
 * @param status  - success/failure (used to set icon)
 */
public void showAlertDialog(Context context, String title, String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting alert dialog icon
    alertDialog.setIcon((status) ? R.drawable.transparentlogo : R.drawable.transparentlogo);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            MainActivity.this.finish();
            dialog.dismiss();

        }
    });

    // Showing Alert Message
    alertDialog.show();
}