Example usage for android.app AlertDialog setButton

List of usage examples for android.app AlertDialog setButton

Introduction

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

Prototype

public void setButton(int whichButton, CharSequence text, OnClickListener listener) 

Source Link

Document

Set a listener to be invoked when the positive button of the dialog is pressed.

Usage

From source file:RhodesService.java

private File downloadPackage(String url) throws IOException {
    final Context ctx = RhodesActivity.getContext();

    final Thread thisThread = Thread.currentThread();

    final Runnable cancelAction = new Runnable() {
        public void run() {
            thisThread.interrupt();/*from w  ww .  j  av a2  s .c om*/
        }
    };

    BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_ASK_CANCEL_DOWNLOAD)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                builder.setMessage("Cancel download?");
                AlertDialog dialog = builder.create();
                dialog.setButton(AlertDialog.BUTTON_POSITIVE, ctx.getText(android.R.string.yes),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                cancelAction.run();
                            }
                        });
                dialog.setButton(AlertDialog.BUTTON_NEGATIVE, ctx.getText(android.R.string.no),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // Nothing
                            }
                        });
                dialog.show();
            } else if (action.equals(ACTION_CANCEL_DOWNLOAD)) {
                cancelAction.run();
            }
        }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_ASK_CANCEL_DOWNLOAD);
    filter.addAction(ACTION_CANCEL_DOWNLOAD);
    ctx.registerReceiver(downloadReceiver, filter);

    File tmpFile = null;
    InputStream is = null;
    OutputStream os = null;
    try {
        updateDownloadNotification(url, -1, 0);

        /*
        List<File> folders = new ArrayList<File>();
        folders.add(Environment.getDownloadCacheDirectory());
        folders.add(Environment.getDataDirectory());
        folders.add(ctx.getCacheDir());
        folders.add(ctx.getFilesDir());
        try {
           folders.add(new File(ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0).dataDir));
        } catch (NameNotFoundException e1) {
           // Ignore
        }
        folders.add(Environment.getExternalStorageDirectory());
                
        for (File folder : folders) {
           File tmpRootFolder = new File(folder, "rhodownload");
           File tmpFolder = new File(tmpRootFolder, ctx.getPackageName());
           if (tmpFolder.exists())
              deleteFilesInFolder(tmpFolder.getAbsolutePath());
           else
              tmpFolder.mkdirs();
                   
           File of = new File(tmpFolder, UUID.randomUUID().toString() + ".apk");
           Logger.D(TAG, "Check path " + of.getAbsolutePath() + "...");
           try {
              os = new FileOutputStream(of);
           }
           catch (FileNotFoundException e) {
              Logger.D(TAG, "Can't open file " + of.getAbsolutePath() + ", check next path");
              continue;
           }
           Logger.D(TAG, "File " + of.getAbsolutePath() + " succesfully opened for write, start download app");
                   
           tmpFile = of;
           break;
        }
        */

        tmpFile = ctx.getFileStreamPath(UUID.randomUUID().toString() + ".apk");
        os = ctx.openFileOutput(tmpFile.getName(), Context.MODE_WORLD_READABLE);

        Logger.D(TAG, "Download " + url + " to " + tmpFile.getAbsolutePath() + "...");

        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        int totalBytes = -1;
        if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            totalBytes = httpConn.getContentLength();
        }
        is = conn.getInputStream();

        int downloaded = 0;
        updateDownloadNotification(url, totalBytes, downloaded);

        long prevProgress = 0;
        byte[] buf = new byte[65536];
        for (;;) {
            if (thisThread.isInterrupted()) {
                tmpFile.delete();
                Logger.D(TAG, "Download of " + url + " was canceled");
                return null;
            }
            int nread = is.read(buf);
            if (nread == -1)
                break;

            //Logger.D(TAG, "Downloading " + url + ": got " + nread + " bytes...");
            os.write(buf, 0, nread);

            downloaded += nread;
            if (totalBytes > 0) {
                // Update progress view only if current progress is greater than
                // previous by more than 10%. Otherwise, if update it very frequently,
                // user will no have chance to click on notification view and cancel if need
                long progress = downloaded * 10 / totalBytes;
                if (progress > prevProgress) {
                    updateDownloadNotification(url, totalBytes, downloaded);
                    prevProgress = progress;
                }
            }
        }

        Logger.D(TAG, "File stored to " + tmpFile.getAbsolutePath());

        return tmpFile;
    } catch (IOException e) {
        if (tmpFile != null)
            tmpFile.delete();
        throw e;
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
        }

        mNM.cancel(DOWNLOAD_PACKAGE_ID);
        ctx.unregisterReceiver(downloadReceiver);
    }
}

From source file:com.xperia64.rompatcher.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    staticThis = MainActivity.this;

    setContentView(R.layout.main);// w  w w .  j a  v  a2  s  .c  om
    // Load native libraries
    try {
        System.loadLibrary("apsn64patcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab apspatcher!");
    }
    try {
        System.loadLibrary("ipspatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab ipspatcher!");
    }
    try {
        System.loadLibrary("ipspatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab ipspatcher!");
    }
    try {
        System.loadLibrary("upspatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab upspatcher!");
    }
    try {
        System.loadLibrary("xdelta3patcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab xdelta3patcher!");
    }
    try {
        System.loadLibrary("bpspatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab bpspatcher!");
    }
    try {
        System.loadLibrary("bzip2");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab bzip2!");
    }
    try {
        System.loadLibrary("bsdiffpatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab bsdiffpatcher!");
    }
    try {
        System.loadLibrary("ppfpatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab ppfpatcher!");
    }
    try {
        System.loadLibrary("ips32patcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab ips32patcher!");
    }
    try {
        System.loadLibrary("glib-2.0");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab glib-2.0!");
    }
    try {
        System.loadLibrary("gmodule-2.0");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab gmodule-2.0!");
    }
    try {
        System.loadLibrary("edsio");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab edsio!");
    }
    try {
        System.loadLibrary("xdelta1patcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab ips32patcher!");
    }
    try {
        System.loadLibrary("ips32patcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab ips32patcher!");
    }
    try {
        System.loadLibrary("ecmpatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab ecmpatcher!");
    }
    try {
        System.loadLibrary("dpspatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab dpspatcher!");
    }
    try {
        System.loadLibrary("dldipatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab dldipatcher!");
    }
    try {
        System.loadLibrary("xpcpatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab xpcpatcher!");
    }
    try {
        System.loadLibrary("asarpatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab asarpatcher!");
    }
    try {
        System.loadLibrary("asmpatcher");
    } catch (UnsatisfiedLinkError e) {
        Log.e("Bad:", "Cannot grab asmpatcher!");
    }
    c = (CheckBox) findViewById(R.id.backupCheckbox);
    d = (CheckBox) findViewById(R.id.altNameCheckbox);
    r = (CheckBox) findViewById(R.id.ignoreCRC);
    e = (CheckBox) findViewById(R.id.fileExtCheckbox);
    ed = (EditText) findViewById(R.id.txtOutFile);

    final Button romButton = (Button) findViewById(R.id.romButton);
    romButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Globals.mode = true;
            Intent intent = new Intent(staticThis, FileBrowserActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivityForResult(intent, 1);

        }
    });
    final Button patchButton = (Button) findViewById(R.id.patchButton);
    patchButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Globals.mode = false;
            Intent intent = new Intent(staticThis, FileBrowserActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivityForResult(intent, 1);
        }
    });
    final ImageButton bkHelp = (ImageButton) findViewById(R.id.backupHelp);
    bkHelp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            AlertDialog dialog = new AlertDialog.Builder(staticThis).create();
            dialog.setTitle(getResources().getString(R.string.bkup_rom));
            dialog.setMessage(getResources().getString(R.string.bkup_rom_desc));
            dialog.setCancelable(true);
            dialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.ok),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int buttonId) {

                        }
                    });
            dialog.show();
        }
    });
    final ImageButton altNameHelp = (ImageButton) findViewById(R.id.outfileHelp);
    altNameHelp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            AlertDialog dialog = new AlertDialog.Builder(staticThis).create();
            dialog.setTitle(getResources().getString(R.string.rename1));
            dialog.setMessage(getResources().getString(R.string.rename_desc));
            dialog.setCancelable(true);
            dialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.ok),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int buttonId) {

                        }
                    });
            dialog.show();
        }
    });
    final ImageButton chkHelp = (ImageButton) findViewById(R.id.ignoreHelp);
    chkHelp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            AlertDialog dialog = new AlertDialog.Builder(staticThis).create();
            dialog.setTitle(getResources().getString(R.string.ignoreChks));
            dialog.setMessage(getResources().getString(R.string.ignoreChks_desc));
            dialog.setCancelable(true);
            dialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.ok),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int buttonId) {

                        }
                    });
            dialog.show();
        }
    });

    InputFilter filter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            for (int i = start; i < end; i++) {
                String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*";
                if (IC.contains("*" + source.charAt(i) + "*")) {
                    return "";
                }
            }
            return null;
        }
    };
    ed.setFilters(new InputFilter[] { filter });
    c.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (((CheckBox) v).isChecked()) {
                d.setEnabled(true);
                if (d.isChecked()) {
                    ed.setEnabled(true);
                    e.setEnabled(true);
                }
            } else {
                d.setEnabled(false);
                ed.setEnabled(false);
                e.setEnabled(false);
            }
        }
    });
    d.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (((CheckBox) v).isChecked()) {
                ed.setEnabled(true);
                e.setEnabled(true);
            } else {
                e.setEnabled(false);
                ed.setEnabled(false);
            }
        }
    });
    final Button applyButton = (Button) findViewById(R.id.applyPatch);
    applyButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Warn about patching archives.
            if (Globals.fileToPatch.toLowerCase(Locale.US).endsWith(".7z")
                    || Globals.fileToPatch.toLowerCase(Locale.US).endsWith(".zip")
                    || Globals.fileToPatch.toLowerCase(Locale.US).endsWith(".rar")) {
                AlertDialog dialog = new AlertDialog.Builder(staticThis).create();
                dialog.setTitle(getResources().getString(R.string.warning));
                dialog.setMessage(getResources().getString(R.string.zip_warning_desc));
                dialog.setCancelable(false);
                dialog.setButton(DialogInterface.BUTTON_POSITIVE,
                        getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int buttonId) {

                                patchCheck();
                            }
                        });
                dialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                        getResources().getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int buttonId) {
                                Toast t = Toast.makeText(staticThis, getResources().getString(R.string.nopatch),
                                        Toast.LENGTH_SHORT);
                                t.show();

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

        }
    });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Uggh.
        requestPermissions();
    }
}

From source file:org.odk.collect.android.activities.MainMenuActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case PASSWORD_DIALOG:

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog passwordDialog = builder.create();
        passwordDialog.setTitle(getString(R.string.enter_admin_password));
        LayoutInflater inflater = this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialogbox_layout, null);
        passwordDialog.setView(dialogView, 20, 10, 20, 10);
        final CheckBox checkBox = (CheckBox) dialogView.findViewById(R.id.checkBox);
        final EditText input = (EditText) dialogView.findViewById(R.id.editText);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override/*from   www  .  jav  a 2s.co m*/
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!checkBox.isChecked()) {
                    input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {
                    input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
        passwordDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String value = input.getText().toString();
                        String pw = adminPreferences.getString(AdminKeys.KEY_ADMIN_PW, "");
                        if (pw.compareTo(value) == 0) {
                            Intent i = new Intent(getApplicationContext(), AdminPreferencesActivity.class);
                            startActivity(i);
                            input.setText("");
                            passwordDialog.dismiss();
                        } else {
                            ToastUtils.showShortToast(R.string.admin_password_incorrect);
                            Collect.getInstance().getActivityLogger().logAction(this, "adminPasswordDialog",
                                    "PASSWORD_INCORRECT");
                        }
                    }
                });

        passwordDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel),
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        Collect.getInstance().getActivityLogger().logAction(this, "adminPasswordDialog",
                                "cancel");
                        input.setText("");
                        return;
                    }
                });

        passwordDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        return passwordDialog;

    }
    return null;
}

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

public void saveCfg() {
    localfinished = false;/* w w w.jav a2s .com*/
    if (Globals.isMidi(currSongName) && Globals.isPlaying == 0) {

        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("Save Cfg");
        alert.setMessage("Save a MIDI configuration file");
        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                    int dend) {
                for (int i = start; i < end; i++) {
                    String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*";
                    if (IC.contains("*" + source.charAt(i) + "*")) {
                        return "";
                    }
                }
                return null;
            }
        };
        // Set an EditText view to get user input 
        final EditText input = new EditText(this);
        input.setFilters(new InputFilter[] { filter });
        alert.setView(input);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String value = input.getText().toString();
                if (!value.toLowerCase(Locale.US).endsWith(Globals.compressCfg ? ".tzf" : ".tcf"))
                    value += (Globals.compressCfg ? ".tzf" : ".tcf");
                String parent = currSongName.substring(0, currSongName.lastIndexOf('/') + 1);
                boolean aWrite = true;
                boolean alreadyExists = new File(parent + value).exists();
                String needRename = null;
                String probablyTheRoot = "";
                String probablyTheDirectory = "";
                try {
                    new FileOutputStream(parent + value, true).close();
                } catch (FileNotFoundException e) {
                    aWrite = false;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (!alreadyExists && aWrite)
                    new File(parent + value).delete();
                if (aWrite && new File(parent).canWrite()) {
                    value = parent + value;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) {
                    //TODO
                    // Write the file to getExternalFilesDir, then move it with the Uri
                    // We need to tell JNIHandler that movement is needed.

                    String[] tmp = Globals.getDocFilePaths(TimidityActivity.this, parent);
                    probablyTheDirectory = tmp[0];
                    probablyTheRoot = tmp[1];
                    if (probablyTheDirectory.length() > 1) {
                        needRename = parent
                                .substring(parent.indexOf(probablyTheRoot) + probablyTheRoot.length()) + value;
                        value = probablyTheDirectory + '/' + value;
                    } else {
                        value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value;
                        return;
                    }
                } else {
                    value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value;
                }
                final String finalval = value;
                final boolean canWrite = aWrite;
                final String needToRename = needRename;
                final String probRoot = probablyTheRoot;
                if (new File(finalval).exists()
                        || (new File(probRoot + needRename).exists() && needToRename != null)) {
                    AlertDialog dialog2 = new AlertDialog.Builder(TimidityActivity.this).create();
                    dialog2.setTitle("Warning");
                    dialog2.setMessage("Overwrite config file?");
                    dialog2.setCancelable(false);
                    dialog2.setButton(DialogInterface.BUTTON_POSITIVE,
                            getResources().getString(android.R.string.yes),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int buttonId) {
                                    if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        if (needToRename != null) {
                                            Globals.tryToDeleteFile(TimidityActivity.this,
                                                    probRoot + needToRename);
                                            Globals.tryToDeleteFile(TimidityActivity.this, finalval);
                                        } else {
                                            Globals.tryToDeleteFile(TimidityActivity.this, finalval);
                                        }
                                    } else {
                                        new File(finalval).delete();
                                    }
                                    saveCfgPart2(finalval, needToRename);
                                }
                            });
                    dialog2.setButton(DialogInterface.BUTTON_NEGATIVE,
                            getResources().getString(android.R.string.no),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int buttonId) {

                                }
                            });
                    dialog2.show();
                } else {
                    saveCfgPart2(finalval, needToRename);
                }
            }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                // Canceled.
            }
        });

        alerty = alert.show();
    }
}

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

public void dynExport() {
    localfinished = false;/*from ww  w .j  ava 2s . c o m*/
    if (Globals.isMidi(currSongName) && Globals.isPlaying == 0) {

        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle(getResources().getString(R.string.dynex_alert1));
        alert.setMessage(getResources().getString(R.string.dynex_alert1_msg));
        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                    int dend) {
                for (int i = start; i < end; i++) {
                    String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*";
                    if (IC.contains("*" + source.charAt(i) + "*")) {
                        return "";
                    }
                }
                return null;
            }
        };
        final EditText input = new EditText(this);
        input.setFilters(new InputFilter[] { filter });
        alert.setView(input);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String value = input.getText().toString();
                if (!value.toLowerCase(Locale.US).endsWith(".wav"))
                    value += ".wav";
                String parent = currSongName.substring(0, currSongName.lastIndexOf('/') + 1);
                boolean alreadyExists = new File(parent + value).exists();
                boolean aWrite = true;
                String needRename = null;
                String probablyTheRoot = "";
                String probablyTheDirectory = "";
                try {
                    new FileOutputStream(parent + value, true).close();
                } catch (FileNotFoundException e) {
                    aWrite = false;
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (aWrite && !alreadyExists)
                    new File(parent + value).delete();

                if (aWrite && new File(parent).canWrite()) {
                    value = parent + value;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) {
                    String[] tmp = Globals.getDocFilePaths(TimidityActivity.this, parent);
                    probablyTheDirectory = tmp[0];
                    probablyTheRoot = tmp[1];
                    if (probablyTheDirectory.length() > 1) {
                        needRename = parent
                                .substring(parent.indexOf(probablyTheRoot) + probablyTheRoot.length()) + value;
                        value = probablyTheDirectory + '/' + value;
                    } else {
                        value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value;
                    }
                } else {
                    value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value;
                }
                final String finalval = value;
                final boolean canWrite = aWrite;
                final String needToRename = needRename;
                final String probRoot = probablyTheRoot;
                if (new File(finalval).exists()
                        || (new File(probRoot + needRename).exists() && needToRename != null)) {
                    AlertDialog dialog2 = new AlertDialog.Builder(TimidityActivity.this).create();
                    dialog2.setTitle(getResources().getString(R.string.warning));
                    dialog2.setMessage(getResources().getString(R.string.dynex_alert2_msg));
                    dialog2.setCancelable(false);
                    dialog2.setButton(DialogInterface.BUTTON_POSITIVE,
                            getResources().getString(android.R.string.yes),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int buttonId) {
                                    if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        if (needToRename != null) {
                                            Globals.tryToDeleteFile(TimidityActivity.this,
                                                    probRoot + needToRename);
                                            Globals.tryToDeleteFile(TimidityActivity.this, finalval);
                                        } else {
                                            Globals.tryToDeleteFile(TimidityActivity.this, finalval);
                                        }
                                    } else {
                                        new File(finalval).delete();
                                    }
                                    saveWavPart2(finalval, needToRename);
                                }
                            });
                    dialog2.setButton(DialogInterface.BUTTON_NEGATIVE,
                            getResources().getString(android.R.string.no),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int buttonId) {

                                }
                            });
                    dialog2.show();
                } else {
                    saveWavPart2(finalval, needToRename);
                }

            }
        });

        alert.setNegativeButton(getResources().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                    }
                });

        alerty = alert.show();

    }
}

From source file:info.zamojski.soft.towercollector.MainActivity.java

private void displayNotCompatibleDialog() {
    // check if displayed in this app run
    if (showNotCompatibleDialog) {
        // check if not disabled in preferences
        boolean showCompatibilityWarningEnabled = MyApplication.getPreferencesProvider()
                .getShowCompatibilityWarning();
        if (showCompatibilityWarningEnabled) {
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            // check if device contains telephony hardware (some tablets doesn't report even if have)
            // NOTE: in the future this may need to be expanded when new specific features appear
            PackageManager packageManager = getPackageManager();
            boolean noRadioDetected = !(packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
                    && (packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_GSM)
                            || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)));
            // show dialog if something is not supported
            if (noRadioDetected) {
                Log.d("displayNotCompatibleDialog(): Not compatible because of radio: %s, phone type: %s",
                        noRadioDetected, telephonyManager.getPhoneType());
                //use custom layout to show "don't show this again" checkbox
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                LayoutInflater inflater = LayoutInflater.from(this);
                View dialogLayout = inflater.inflate(R.layout.dont_show_again_dialog, null);
                final CheckBox dontShowAgainCheckbox = (CheckBox) dialogLayout
                        .findViewById(R.id.dont_show_again_dialog_checkbox);
                dialogBuilder.setView(dialogLayout);
                AlertDialog alertDialog = dialogBuilder.create();
                alertDialog.setCanceledOnTouchOutside(true);
                alertDialog.setCancelable(true);
                alertDialog.setTitle(R.string.main_dialog_not_compatible_title);
                StringBuilder stringBuilder = new StringBuilder(
                        getString(R.string.main_dialog_not_compatible_begin));
                if (noRadioDetected) {
                    stringBuilder.append(getString(R.string.main_dialog_no_compatible_mobile_radio_message));
                }//from   w w  w .ja v a2  s.co  m
                // text set this way to prevent checkbox from disappearing when text is too long
                TextView messageTextView = (TextView) dialogLayout
                        .findViewById(R.id.dont_show_again_dialog_textview);
                messageTextView.setText(stringBuilder.toString());
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_ok),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                boolean dontShowAgainCheckboxChecked = dontShowAgainCheckbox.isChecked();
                                Log.d("displayNotCompatibleDialog(): Don't show again checkbox checked = %s",
                                        dontShowAgainCheckboxChecked);
                                if (dontShowAgainCheckboxChecked) {
                                    MyApplication.getPreferencesProvider().setShowCompatibilityWarning(false);
                                }
                            }
                        });
                alertDialog.show();
            }
        }
        showNotCompatibleDialog = false;
    }
}

From source file:com.tweetlanes.android.core.view.BaseLaneActivity.java

public void shareSelected(TwitterStatus status) {

    if (status != null) {

        App application = (App) getApplication();
        AccountDescriptor currentAccount = application.getCurrentAccount();

        String url;/*from  w w w  .j  a  va  2s  . com*/
        String shareText;
        if (currentAccount.getSocialNetType() == SocialNetConstant.Type.Twitter) {
            url = status.getTwitterComStatusUrl();
            shareText = getString(R.string.share_tweet_link);
        } else {
            url = status.getAdnStatusUrl();
            shareText = getString(R.string.share_tweet_post);
        }
        final String statusUrl = url;
        final String statusText = status.mStatus;
        final ArrayList<String> urls = Util.getUrlsInString(status.mStatus);

        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle(getString(R.string.alert_share_title));
        alertDialog.setMessage(getString(R.string.alert_share_message));
        alertDialog.setIcon(AppSettings.get().getCurrentTheme() == AppSettings.Theme.Holo_Dark
                || AppSettings.get().getCurrentTheme() == AppSettings.Theme.Holo_Light_DarkAction
                        ? R.drawable.ic_action_share_dark
                        : R.drawable.ic_action_share_light);
        // TODO: The order these buttons are set looks wrong, but appears
        // correctly. Have to ensure this is consistent on other devices.
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.share_tweet),
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        shareText(statusText);
                    }
                });

        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, shareText,
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        shareText(statusUrl);
                    }
                });

        if (urls != null && urls.size() > 0) {
            alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
                    getString(urls.size() == 1 ? R.string.share_link : R.string.share_first_link),
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            shareText(urls.get(0));
                        }
                    });
        }

        alertDialog.show();
    }
}

From source file:org.opendatakit.survey.android.activities.MainMenuActivity.java

protected void createPasswordDialog() {
    if (mAlertDialog != null) {
        mAlertDialog.dismiss();//from w ww  .  ja  va2 s . c  o  m
        mAlertDialog = null;
    }
    final AlertDialog passwordDialog = new AlertDialog.Builder(this).create();

    passwordDialog.setTitle(getString(R.string.enter_admin_password));
    final EditText input = new EditText(this);
    input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
    input.setTransformationMethod(PasswordTransformationMethod.getInstance());
    passwordDialog.setView(input, 20, 10, 20, 10);

    passwordDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String value = input.getText().toString();
                    String pw = PropertiesSingleton.getProperty(appName, AdminPreferencesActivity.KEY_ADMIN_PW);
                    if (pw != null && pw.compareTo(value) == 0) {
                        Intent i = new Intent(getApplicationContext(), AdminPreferencesActivity.class);
                        // TODO: convert this activity into a preferences fragment
                        i.putExtra(APP_NAME, getAppName());
                        startActivity(i);
                        input.setText("");
                        passwordDialog.dismiss();
                    } else {
                        Toast.makeText(MainMenuActivity.this, getString(R.string.admin_password_incorrect),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });

    passwordDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel),
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    input.setText("");
                    return;
                }
            });

    passwordDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    mAlertDialog = passwordDialog;
    mAlertDialog.show();
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Creates and shows a custom Alert dialog that will execute
 * the actions specified for positive, negative and 
 * neutral buttons.//  w  w  w  .  ja v  a2s . c o m
 * 
 * @param context
 * @param title
 * @param message
 * @param positiveBtnActions   Can be null. When null button is not shown.
 * @param negativeBtnActions   Can be null. When null button is not shown.
 * @param neutralBtnActions   Can be null.
 */
public static void dialog_showCustomActionsDialog(Context context, String title, String message,
        String positiveBtnText, final Runnable positiveBtnActions, String negativeBtnText,
        final Runnable negativeBtnActions, String neutralBtnText, final Runnable neutralBtnActions) {

    AlertDialog dialog = new AlertDialog.Builder(context).create();

    dialog.setTitle(title);
    dialog.setMessage(message);

    dialog.setCancelable(true);
    dialog.setButton(AlertDialog.BUTTON_NEUTRAL, neutralBtnText, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            if (neutralBtnActions != null) {
                neutralBtnActions.run();
            }
            dialog.dismiss();
        }
    });

    if (negativeBtnActions != null) {
        dialog.setButton(AlertDialog.BUTTON_NEGATIVE, negativeBtnText, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                negativeBtnActions.run();
            }
        });
    }

    if (positiveBtnActions != null) {
        dialog.setButton(AlertDialog.BUTTON_POSITIVE, positiveBtnText, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                positiveBtnActions.run();
            }
        });
    }

    dialog.show();
}