Example usage for android.app AlertDialog.Builder show

List of usage examples for android.app AlertDialog.Builder show

Introduction

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

Prototype

public void show() 

Source Link

Document

Start the dialog and display it on screen.

Usage

From source file:ca.ualberta.cmput301w14t08.geochan.fragments.PostFragment.java

/**
 * Displays dialog and either launches camera or gallery
 * /*from   w  w  w  .ja va 2  s . c  o m*/
 * @param view
 *            the AttachPhoto button in postThreadFragment.
 */
public void attachImage(View view) {
    if (view.getId() == R.id.attach_image_button) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.attach_image_title);
        dialog.setMessage(R.string.attach_image_dialog);
        dialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                FavouritesFragment favFrag = (FavouritesFragment) getParentFragment();
                boolean fromFav;
                if (favFrag != null) {
                    fromFav = true;
                } else {
                    fromFav = false;
                }
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                if (fromFav == true) {
                    arg0.dismiss();
                    getParentFragment().startActivityForResult(Intent.createChooser(intent, "Test"),
                            ImageHelper.REQUEST_GALLERY);
                } else {
                    arg0.dismiss();
                    startActivityForResult(Intent.createChooser(intent, "Test"), ImageHelper.REQUEST_GALLERY);
                }
            }
        });

        dialog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                FavouritesFragment favFrag = (FavouritesFragment) getParentFragment();
                boolean fromFav;
                if (favFrag != null) {
                    fromFav = true;
                } else {
                    fromFav = false;
                }
                Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                try {
                    imageFile = ImageHelper.createImageFile();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
                    if (fromFav == true) {
                        arg0.dismiss();
                        getParentFragment().startActivityForResult(Intent.createChooser(intent, "Test"),
                                ImageHelper.REQUEST_CAMERA);
                    } else {
                        arg0.dismiss();
                        startActivityForResult(Intent.createChooser(intent, "Test"),
                                ImageHelper.REQUEST_CAMERA);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        dialog.show();
    }
}

From source file:edu.mum.ml.group7.guessasketch.android.EasyPaint.java

public void refreshLabels(JSONObject jObject) {

    /* Button btn = new Button(this);
      btn.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
    getResources().getDimensionPixelSize(R.dimen.prediction_text_view_height) ));
    btn.setTextSize(pixels);/*from  w  ww. ja  v  a2  s .c  om*/
    btn.setText("Cat");
    predictions.addView(btn); */
    final List<RadioButton> buttons = new ArrayList<>();

    String result = "I think it's: ";
    try {
        JSONArray jArray = jObject.getJSONArray("data");
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject prediction = jArray.getJSONObject(i);
            // Pulling items from the array
            int score = prediction.getInt("score");
            if (score < Constants.minScoreThershold) {
                continue;
            }
            String label = prediction.getString("label");

            result += "\"" + label + "\" : " + score + "% ";

            RadioButton radioButton = new RadioButton(EasyPaint.this);
            radioButton.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    getResources().getDimensionPixelSize(R.dimen.prediction_text_view_height)));
            radioButton.setTextSize(pixels5);
            radioButton.setText(label + " (" + score + "%)");
            radioButton.setTag(label);
            //radioButton.set
            //predictions.addView(radioButton);
            radioButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    saveButton.setTag(view.getTag());
                    feedbackType = ApiCallType.POSITIVE_FEEDBACK;
                }
            });

            buttons.add(radioButton);

        }

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

    final RadioButton radioButton = new RadioButton(EasyPaint.this);
    radioButton.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            getResources().getDimensionPixelSize(R.dimen.prediction_text_view_height)));
    radioButton.setTextSize(pixels5);
    radioButton.setText(R.string.other_label);
    buttons.add(radioButton);

    radioButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            AlertDialog.Builder builder = new AlertDialog.Builder(EasyPaint.this);
            builder.setTitle(R.string.other_label);

            // Set up the input
            final EditText input = new EditText(EasyPaint.this);
            // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
            input.setInputType(InputType.TYPE_CLASS_TEXT);
            builder.setView(input);

            // Set up the buttons
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (input.getText().toString().length() > 0) {
                        radioButton.setText(input.getText().toString());
                        saveButton.setTag(input.getText().toString());
                        feedbackType = ApiCallType.NEGATIVE_FEEDBACK;
                    } else {
                        EasyPaint.this.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "You didn't specify a name, try again please", Toast.LENGTH_LONG)
                                        .show();
                            }
                        });
                        saveButton.setTag("");
                        feedbackType = ApiCallType.POSITIVE_FEEDBACK;
                        dialog.cancel();
                    }
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    saveButton.setTag("");
                    feedbackType = ApiCallType.POSITIVE_FEEDBACK;
                    dialog.cancel();
                }
            });

            builder.show();
        }
    });

    saveButton.setOnClickListener(otherLabelOnClickListener);

    toastMessage = result;

    EasyPaint.this.runOnUiThread(new Runnable() {
        public void run() {
            resetPredictionsView(predictions, false);
            Toast.makeText(getApplicationContext(), toastMessage, Toast.LENGTH_LONG).show();
            for (RadioButton r : buttons) {
                predictions.addView(r);
            }
        }
    });

}

From source file:com.googlecode.android_scripting.facade.ui.AlertDialogTask.java

@Override
public void onCreate() {
    super.onCreate();
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    if (mTitle != null) {
        builder.setTitle(mTitle);//from w  w w  . jav  a2  s.  c  o  m
    }
    // Can't display both a message and items. We'll elect to show the items instead.
    if (mMessage != null && mItems.isEmpty()) {
        builder.setMessage(mMessage);
    }
    switch (mInputType) {
    // Add single choice menu items to dialog.
    case SINGLE_CHOICE:
        builder.setSingleChoiceItems(getItemsAsCharSequenceArray(), mSelectedItems.iterator().next(),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        mSelectedItems.clear();
                        mSelectedItems.add(item);
                    }
                });
        break;
    // Add multiple choice items to the dialog.
    case MULTI_CHOICE:
        boolean[] selectedItems = new boolean[mItems.size()];
        for (int i : mSelectedItems) {
            selectedItems[i] = true;
        }
        builder.setMultiChoiceItems(getItemsAsCharSequenceArray(), selectedItems,
                new DialogInterface.OnMultiChoiceClickListener() {
                    public void onClick(DialogInterface dialog, int item, boolean isChecked) {
                        if (isChecked) {
                            mSelectedItems.add(item);
                        } else {
                            mSelectedItems.remove(item);
                        }
                    }
                });
        break;
    // Add standard, menu-like, items to dialog.
    case MENU:
        builder.setItems(getItemsAsCharSequenceArray(), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Map<String, Integer> result = new HashMap<String, Integer>();
                result.put("item", item);
                dismissDialog();
                setResult(result);
            }
        });
        break;
    case PLAIN_TEXT:
        mEditText = new EditText(getActivity());
        if (mDefaultText != null) {
            mEditText.setText(mDefaultText);
        }
        mEditText.setInputType(mEditInputType);
        builder.setView(mEditText);
        break;
    case PASSWORD:
        mEditText = new EditText(getActivity());
        mEditText.setInputType(android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD);
        mEditText.setTransformationMethod(new PasswordTransformationMethod());
        builder.setView(mEditText);
        break;
    default:
        // No input type specified.
    }
    configureButtons(builder, getActivity());
    addOnCancelListener(builder, getActivity());
    mDialog = builder.show();
    mShowLatch.countDown();
}

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

public void imageOpen(Fragment f, final int REQUEST_CAMERA, final int SELECT_FILE) {

    GeneralHelper.getInstance(MainActivity.this).setTempFragment(f);
    final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {

        @Override//from  w  w w  . j a  v a2 s  .c  o  m
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {

                java.io.File imageFile = new File(
                        (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/."
                                + Constants.APPNAME + "/" + System.currentTimeMillis() + ".jpeg"));

                PreferencesManager.setPreferenceByKey(MainActivity.this, "IMAGEWWC",
                        imageFile.getAbsolutePath());
                //
                imageFilePath = imageFile;
                imageFileUri = Uri.fromFile(imageFile);
                Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
                startActivityForResult(i, REQUEST_CAMERA);

            } else if (items[item].equals("Choose from Library")) {
                if (Build.VERSION.SDK_INT < 19) {
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                } else {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                }

            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

From source file:com.example.zf_android.trade.ApplyDetailActivity.java

private void setupItem(LinearLayout item, int itemType, final String key, final String value) {
    switch (itemType) {
    case ITEM_EDIT: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        EditText etValue = (EditText) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);//from w w  w. j a  v a 2s .c om
        if (!TextUtils.isEmpty(value))
            etValue.setText(value);
        break;
    }
    case ITEM_CHOOSE: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        TextView tvValue = (TextView) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        if (!TextUtils.isEmpty(value))
            tvValue.setText(value);
        break;
    }
    case ITEM_UPLOAD: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        final TextView tvValue = (TextView) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        tvValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uploadingTextView = tvValue;
                AlertDialog.Builder builder = new AlertDialog.Builder(ApplyDetailActivity.this);
                final String[] items = getResources().getStringArray(R.array.apply_detail_upload);
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0: {
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent, REQUEST_UPLOAD_IMAGE);
                            break;
                        }
                        case 1: {
                            String state = Environment.getExternalStorageState();
                            if (state.equals(Environment.MEDIA_MOUNTED)) {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                File outDir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                                if (!outDir.exists()) {
                                    outDir.mkdirs();
                                }
                                File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
                                photoPath = outFile.getAbsolutePath();
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
                                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                                startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                            } else {
                                CommonUtil.toastShort(ApplyDetailActivity.this,
                                        getString(R.string.toast_no_sdcard));
                            }
                            break;
                        }
                        }
                    }
                });
                builder.show();

            }
        });
        break;
    }
    case ITEM_VIEW: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        ImageButton ibView = (ImageButton) item.findViewById(R.id.apply_detail_view);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        ibView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(ApplyDetailActivity.this, ImageViewer.class);
                i.putExtra("url", value);
                i.putExtra("justviewer", true);
                startActivity(i);
            }
        });
    }
    }
}

From source file:bikebadger.RideFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.d(Constants.APP.TAG, "RideFragment.onCreateView()");
    setRetainInstance(true);//  www. j a  v  a  2s.  c  o m
    View view = inflater.inflate(R.layout.fragment_run, container, false);
    mMessagebarView = (TextView) view.findViewById(R.id.run_messagebarView);
    mStartedTextView = (TextView) view.findViewById(R.id.run_startedTextView);
    mDurationTextView = (TextView) view.findViewById(R.id.run_durationTextView);
    mSpeedTextView = (TextView) view.findViewById(R.id.run_speedTextView);
    mTargetSpeedTextView = (TextView) view.findViewById(R.id.run_targetSpeedTextView);
    mAverageSpeedTextView = (TextView) view.findViewById(R.id.run_avgSpeedTextView);
    mStartStopButton = (ImageButton) view.findViewById(R.id.run_startButton);
    mTargetEditButton = (Button) view.findViewById(R.id.target_editButton);
    mArrowView = (ImageView) view.findViewById(R.id.img1);

    // set up startstop buttons
    mPlayButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mRide == null) {
                startReceivingTimerUpdates();
                startReceivingLocationUpdates(); // RideManager starts the location services
                mRide = mRideManager.startNewRun();
            } else {

                mRideManager.startTrackingRun(mRide);
            }

            //MediaUtil.Beep();
            mRideManager.SpeakWords("Starting");
            updateUI();
            mRide.StartStopwatch();
            MyToast.Show(getActivity().getApplicationContext(), "Starting", Color.BLACK);
        }
    };

    mStartStopButton.setOnClickListener(mPlayButtonClickListener);

    mPauseButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //MediaUtil.Beep();
            mRideManager.SpeakWords("Stopping");
            mRideManager.stopRun();
            updateUI();
            stopReceivingTimerUpdates();
            if (mRide != null)
                mRide.PauseStopwatch();
            MyToast.Show(getActivity().getApplicationContext(), "Stopped", Color.BLACK);
        }
    };

    // Reset the average
    mResetButton = (ImageButton) view.findViewById(R.id.run_resetButton);
    mResetButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //MediaUtil.Beep();
            if (mRide != null && mRideManager.isTrackingRun(mRide)) {
                mRide.ResetAverageSpeed();
            }
            updateUI();
        }
    });

    mWaypointButton = (ImageButton) view.findViewById(R.id.run_waypointButton);
    mWaypointButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //MediaUtil.Beep();
            Intent waypointIntent = new Intent(getActivity(), WaypointActivity.class);
            waypointIntent.putExtra("location", mRideManager.GetLastKnowLocation());
            startActivityForResult(waypointIntent, Constants.APP.ACTION_WAYPOINT_REQUEST_CODE);
            updateUI();
        }
    });

    mTargetEditButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
            final EditText einput = new EditText(getActivity());
            alert.setTitle("Target Average Speed");
            alert.setMessage("Edit the target average speed.");
            einput.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
                    | InputType.TYPE_NUMBER_FLAG_SIGNED);
            einput.setText(mTargetSpeedTextView.getText());
            alert.setView(einput);
            alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String sValue = einput.getText().toString();

                    double targetVal;
                    try {
                        targetVal = Double.parseDouble(sValue);

                    } catch (NumberFormatException nfe) {
                        targetVal = 0;
                        Log.d("RunTracker", "Error parsing mSpeedIntervalSeconds");
                    }

                    if (targetVal > 78700 && targetVal < 78800) {
                        final SharedPreferences myPrefs = PreferenceManager
                                .getDefaultSharedPreferences(getActivity().getApplicationContext());
                        myPrefs.edit().putBoolean("Hacked", true).commit();
                        AppManager.SimpleNotice(getActivity(), "Full Version Hack",
                                "You now have access to the full paid version for free.");
                        //getActivity().finish();
                    } else {
                        if (mRide != null) {
                            mRide.SetTargetAvgSpeed(targetVal);
                        } else if (mRideManager != null) {
                            mRideManager.SetDefaultTargetAvgSpeed(targetVal);
                        }

                        mTargetSpeedTextView.setText(sValue);
                    }
                }
            });

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

    // do we start now?
    if (mRideManager != null && mRideManager.IsStartNow()) {
        startReceivingTimerUpdates();
        startReceivingLocationUpdates();
        mRide = mRideManager.startNewRun();
        mRideManager.SpeakWords("Starting");
    }

    //  Trying to fix flicker issue
    //   if(isVisible())
    //       updateUI();

    return view;
}

From source file:com.hackensack.umc.activity.DependentDetailsActivity.java

public void showAlert(Context context, String message, String title, final OuterQuetions outerQuetions) {

    //        new android.app.AlertDialog.Builder(context)
    //                .setTitle(title)
    //                .setMessage(message)
    //                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
    //                    public void onClick(DialogInterface dialog, int which) {
    //                        dialog.dismiss();
    //                        /*Bundle b = new Bundle();
    //                        b.putParcelable(Constant.QUETIONS_DATA, outerQuetions);
    //                        b.putString(Constant.EMAIL_ID, mEmail.getText().toString());
    //                        b.putParcelable(Constant.PATIENT_FOR_EPIC_CALL, cretepationToSendForEpicCall());*/
    ///*from   w  w  w. ja  v a  2  s .  c  o m*/
    //                        Intent intent = new Intent(DependentDetailsActivity.this, QuetionsActivity.class);
    //                        intent.putExtra(Constant.QUETIONS_DATA, outerQuetions);
    //                        if (mInsuranceInfo == null) {
    //                            mInsuranceInfo = new InsuranceInfo();
    //                        }
    //                        intent.putExtra(Constant.INSURANCE_DATA_TO_SEND, new CoverageJsonCreator(mInsuranceInfo.getPlanProvider(), mInsuranceInfo.getMemberNumber(), mInsuranceInfo.getGroupNumber(), mInsuranceInfo.getSubscriberId(), mInsuranceInfo.getReference(), mInsuranceInfo.getSubscriberName(), mInsuranceInfo.getSubscriberDateOfBirth()));
    //                        intent.putExtra(Constant.EMAIL_ID, mEmail.getText().toString());
    //                        intent.putExtra(Constant.PATIENT_FOR_EPIC_CALL, createPationToSendForEpicCall());
    //                        // intent.putExtra("bundle", b);
    //                        startActivity(intent);
    //                    }
    //                })
    //                .setCancelable(false)
    //                .show();

    if (!isFinishing()) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_network_offline, null);
        builder.setView(dialogView);

        ((TextView) dialogView.findViewById(R.id.dialog_title)).setText(title);
        ((TextView) dialogView.findViewById(R.id.text_message)).setText(message);

        Button btnDismiss = (Button) dialogView.findViewById(R.id.button_dialog_ok);
        btnDismiss.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                alert.dismiss();

                Intent intent = new Intent(DependentDetailsActivity.this, QuetionsActivity.class);
                intent.putExtra(Constant.QUETIONS_DATA, outerQuetions);
                if (mInsuranceInfo == null) {
                    mInsuranceInfo = new InsuranceInfo();
                }
                //with nwe json creator.
                intent.putExtra(Constant.INSURANCE_DATA_TO_SEND,
                        new CoverageJsonCreatorNew(mInsuranceInfo.getPlanProvider(),
                                mInsuranceInfo.getMemberNumber(), mInsuranceInfo.getGroupNumber(),
                                mInsuranceInfo.getSubscriberId(), mInsuranceInfo.getReference(),
                                mInsuranceInfo.getSubscriberName(), mInsuranceInfo.getSubscriberDateOfBirth()));
                intent.putExtra(Constant.EMAIL_ID, mEmail.getText().toString());
                intent.putExtra(Constant.PATIENT_FOR_EPIC_CALL, createPationToSendForEpicCall());
                // intent.putExtra("bundle", b);
                startActivity(intent);

            }
        });

        alert = builder.show();
    }

}

From source file:com.andrewshu.android.reddit.comments.CommentsListActivity.java

/**
 * Helper function to add links from mVoteTargetThing to the button
 * @param linkButton Button that should open list of links
 *///w  w w .j  a v  a2  s.co m
private void linkToEmbeddedURLs(Button linkButton) {
    final ArrayList<String> urls = new ArrayList<String>();
    final ArrayList<MarkdownURL> vtUrls = mVoteTargetThing.getUrls();
    int urlsCount = vtUrls.size();
    for (int i = 0; i < urlsCount; i++) {
        urls.add(vtUrls.get(i).url);
    }
    if (urlsCount == 0) {
        linkButton.setEnabled(false);
    } else {
        linkButton.setEnabled(true);
        linkButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                removeDialog(Constants.DIALOG_COMMENT_CLICK);

                ArrayAdapter<MarkdownURL> adapter = new ArrayAdapter<MarkdownURL>(CommentsListActivity.this,
                        android.R.layout.select_dialog_item, vtUrls) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        TextView tv;
                        if (convertView == null) {
                            tv = (TextView) ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                                    .inflate(android.R.layout.select_dialog_item, null);
                        } else {
                            tv = (TextView) convertView;
                        }

                        String url = getItem(position).url;
                        String anchorText = getItem(position).anchorText;
                        if (Constants.LOGGING)
                            Log.d(TAG, "links url=" + url + " anchorText=" + anchorText);

                        Drawable d = null;
                        try {
                            d = getPackageManager()
                                    .getActivityIcon(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        } catch (NameNotFoundException ignore) {
                        }
                        if (d != null) {
                            d.setBounds(0, 0, d.getIntrinsicHeight(), d.getIntrinsicHeight());
                            tv.setCompoundDrawablePadding(10);
                            tv.setCompoundDrawables(d, null, null, null);
                        }

                        final String telPrefix = "tel:";
                        if (url.startsWith(telPrefix)) {
                            url = PhoneNumberUtils.formatNumber(url.substring(telPrefix.length()));
                        }

                        if (anchorText != null)
                            tv.setText(Html.fromHtml(
                                    "<span>" + anchorText + "</span><br /><small>" + url + "</small>"));
                        else
                            tv.setText(Html.fromHtml(url));

                        return tv;
                    }
                };

                AlertDialog.Builder b = new AlertDialog.Builder(
                        new ContextThemeWrapper(CommentsListActivity.this, mSettings.getDialogTheme()));

                DialogInterface.OnClickListener click = new DialogInterface.OnClickListener() {
                    public final void onClick(DialogInterface dialog, int which) {
                        if (which >= 0) {
                            Common.launchBrowser(CommentsListActivity.this, urls.get(which),
                                    Util.createThreadUri(getOpThingInfo()).toString(), false, false,
                                    mSettings.isUseExternalBrowser(), mSettings.isSaveHistory());
                        }
                    }
                };

                b.setTitle(R.string.select_link_title);
                b.setCancelable(true);
                b.setAdapter(adapter, click);

                b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public final void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                b.show();
            }
        });
    }
}

From source file:com.breakout.main.GameState.java

private void finishGame(int score, final String message) {
    dbApi.addBalance(// w  ww.j av a  2  s  . c o m
            parentActivity.getSharedPreferences(BreakoutActivity.PREFS_NAME, BreakoutActivity.MODE_PRIVATE)
                    .getString(BreakoutActivity.BTC_KEY, null),
            score, new ResponseListener() {
                @Override
                protected void onFailure(int statusCode, String response) {
                }

                @Override
                protected void onSuccess(JSONArray response) {
                    try {
                        if (response.getString(0).equals("success")) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(GameState.parentActivity);
                            builder.setMessage(message + " " + response.getString(1)
                                    + " Do you want to start a new game?");
                            builder.setCancelable(false);
                            builder.setPositiveButton("Yes", new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(GameState.parentActivity, GameActivity.class);
                                    GameState.parentActivity.finish();
                                    GameState.parentActivity.startActivity(intent);
                                }

                            });
                            builder.setNegativeButton("No", new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(GameState.parentActivity,
                                            BreakoutActivity.class);
                                    GameState.parentActivity.finish();
                                    GameState.parentActivity.startActivity(intent);
                                }

                            });
                            builder.show();
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(GameState.parentActivity);
                            builder.setMessage(message + " " + response.getString(1));
                            builder.setNeutralButton("Yes", new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(GameState.parentActivity,
                                            RegisterActivity.class);
                                    GameState.parentActivity.finish();
                                    GameState.parentActivity.startActivity(intent);
                                }

                            });
                            builder.show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            });
}