Example usage for android.app Dialog findViewById

List of usage examples for android.app Dialog findViewById

Introduction

In this page you can find the example usage for android.app Dialog findViewById.

Prototype

@Nullable
public <T extends View> T findViewById(@IdRes int id) 

Source Link

Document

Finds the first descendant view with the given ID or null if the ID is invalid (< 0), there is no matching view in the hierarchy, or the dialog has not yet been fully created (for example, via #show() or #create() ).

Usage

From source file:org.onebusaway.android.ui.TripPlanFragment.java

private void advancedSettings() {

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());

    final TypedArray transitModeResource = getContext().getResources()
            .obtainTypedArray(R.array.transit_mode_array);
    final boolean unitsAreImperial = !PreferenceUtils.getUnitsAreMetricFromPreferences(getContext());

    dialogBuilder.setTitle(R.string.trip_plan_advanced_settings)
            .setView(R.layout.trip_plan_advanced_settings_dialog);

    dialogBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        @Override/*from w  w w . j  av a  2  s  .  c om*/
        public void onClick(DialogInterface dialogInterface, int which) {

            Dialog dialog = (Dialog) dialogInterface;

            boolean optimizeTransfers = ((CheckBox) dialog.findViewById(R.id.checkbox_minimize_transfers))
                    .isChecked();

            Spinner spinnerTravelBy = (Spinner) dialog.findViewById(R.id.spinner_travel_by);

            int modeId = transitModeResource.getResourceId(spinnerTravelBy.getSelectedItemPosition(), 0);

            boolean wheelchair = ((CheckBox) dialog.findViewById(R.id.checkbox_wheelchair_acccesible))
                    .isChecked();

            String maxWalkString = ((EditText) dialog.findViewById(R.id.number_maximum_walk_distance)).getText()
                    .toString();
            double maxWalkDistance;
            if (TextUtils.isEmpty(maxWalkString)) {
                maxWalkDistance = Double.MAX_VALUE;
            } else {
                double d = Double.parseDouble(maxWalkString);
                maxWalkDistance = unitsAreImperial ? ConversionUtils.feetToMeters(d) : d;
            }

            mBuilder.setOptimizeTransfers(optimizeTransfers).setModeSetById(modeId)
                    .setWheelchairAccessible(wheelchair).setMaxWalkDistance(maxWalkDistance);

            checkRequestAndSubmit();
        }
    });

    final AlertDialog dialog = dialogBuilder.create();

    dialog.show();

    CheckBox minimizeTransfersCheckbox = (CheckBox) dialog.findViewById(R.id.checkbox_minimize_transfers);
    Spinner spinnerTravelBy = (Spinner) dialog.findViewById(R.id.spinner_travel_by);
    CheckBox wheelchairCheckbox = (CheckBox) dialog.findViewById(R.id.checkbox_wheelchair_acccesible);
    EditText maxWalkEditText = (EditText) dialog.findViewById(R.id.number_maximum_walk_distance);

    minimizeTransfersCheckbox.setChecked(mBuilder.getOptimizeTransfers());

    wheelchairCheckbox.setChecked(mBuilder.getWheelchairAccessible());

    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.transit_mode_array,
            android.R.layout.simple_spinner_item);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerTravelBy.setAdapter(adapter);

    int modeSetId = mBuilder.getModeSetId();
    if (modeSetId != -1) {
        for (int i = 0; i < transitModeResource.length(); i++) {
            if (transitModeResource.getResourceId(i, -1) == modeSetId) {
                spinnerTravelBy.setSelection(i);
                break;
            }
        }
    }

    Double maxWalk = mBuilder.getMaxWalkDistance();
    if (maxWalk != null && Double.MAX_VALUE != maxWalk) {
        if (unitsAreImperial) {
            maxWalk = ConversionUtils.metersToFeet(maxWalk);
        }
        maxWalkEditText.setText(String.format("%d", maxWalk.longValue()));
    }

    if (unitsAreImperial) {
        TextView label = (TextView) dialog.findViewById(R.id.label_minimum_walk_distance);
        label.setText(getString(R.string.feet_abbreviation));
    }
}

From source file:com.smsc.usuario.ui.MapaActivity.java

public void getDetalle(int posicion) {
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCancelable(false);//  w w  w  . j ava2s.com
    dialog.setContentView(R.layout.dialog_incidente);

    TextView lblAsunto = (TextView) dialog.findViewById(R.id.lblAsunto);
    lblAsunto.setText(lista.get(posicion).getStr_detalle());

    TextView lblNombreInciente = (TextView) dialog.findViewById(R.id.lblNombreInciente);
    lblNombreInciente.setText(lista.get(posicion).getStr_tipo_incidente_nombre());

    TextView lblEstado = (TextView) dialog.findViewById(R.id.lblEstado);
    lblEstado.setText("Enviado");
    if (lista.get(posicion).getInt_estado() == 1)
        lblEstado.setText("En Progreso");
    else if (lista.get(posicion).getInt_estado() == 2)
        lblEstado.setText("Valido");
    else if (lista.get(posicion).getInt_estado() == 3)
        lblEstado.setText("Invalido");
    SimpleDateFormat fecha = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat hora = new SimpleDateFormat("h:mm a");

    TextView lblFecha = (TextView) dialog.findViewById(R.id.lblFecha);
    lblFecha.setText(fecha.format(lista.get(posicion).getDat_fecha_registro()));

    TextView lblHora = (TextView) dialog.findViewById(R.id.lblHora);
    lblHora.setText(hora.format(lista.get(posicion).getDat_fecha_registro()));

    View ViewFoto = (View) dialog.findViewById(R.id.ViewFoto);
    if (lista.get(posicion).getByte_foto() == null) {
        ViewFoto.setVisibility(View.GONE);
    } else {
        ImageView image = (ImageView) dialog.findViewById(R.id.image);
        image.setImageBitmap(Funciones.getBitmap(lista.get(posicion).getByte_foto()));
    }

    View ViewCalificacion = (View) dialog.findViewById(R.id.ViewCalificacion);
    if (lista.get(posicion).getInt_rapides() == 0 && lista.get(posicion).getInt_conformidad() == 0) {
        ViewCalificacion.setVisibility(View.GONE);
    } else {
        RatingBar ratingRapides = (RatingBar) dialog.findViewById(R.id.ratingRapides);
        ratingRapides.setRating(lista.get(posicion).getInt_rapides());

        RatingBar ratingConformidad = (RatingBar) dialog.findViewById(R.id.ratingConformidad);
        ratingConformidad.setRating(lista.get(posicion).getInt_conformidad());
    }

    Button btnAceptar = (Button) dialog.findViewById(R.id.btnAceptar);
    btnAceptar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show();

}

From source file:com.entertailion.android.launcher.Dialogs.java

/**
 * Display dialog to the user for the browser bookmarks. Allow the user to add a
 * browser bookmark to an existing row or a new row.
 * //from  w  ww  . ja  v a2  s  .  c o m
 * @param context
 */
public static void displayAddBrowserBookmark(final Launcher context) {
    final Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.add_browser_bookmarks_list);

    final EditText nameEditText = (EditText) dialog.findViewById(R.id.rowName);
    final RadioButton currentRadioButton = (RadioButton) dialog.findViewById(R.id.currentRadio);
    currentRadioButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // hide the row name edit field if the current row radio button
            // is selected
            nameEditText.setVisibility(View.GONE);
        }

    });
    final RadioButton newRadioButton = (RadioButton) dialog.findViewById(R.id.newRadio);
    newRadioButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // show the row name edit field if the new radio button is
            // selected
            nameEditText.setVisibility(View.VISIBLE);
            nameEditText.requestFocus();
        }

    });

    ListView listView = (ListView) dialog.findViewById(R.id.list);
    final ArrayList<BookmarkInfo> bookmarks = loadBookmarks(context);
    Collections.sort(bookmarks, new Comparator<BookmarkInfo>() {

        @Override
        public int compare(BookmarkInfo lhs, BookmarkInfo rhs) {
            return lhs.getTitle().toLowerCase().compareTo(rhs.getTitle().toLowerCase());
        }

    });
    listView.setAdapter(new BookmarkAdapter(context, bookmarks));
    listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(final AdapterView<?> parent, final View view, final int position,
                final long id) {
            // run in thread since network logic needed to get bookmark icon
            new Thread(new Runnable() {
                public void run() {
                    // if the new row radio button is selected, the user must enter
                    // a name for the new row
                    String name = nameEditText.getText().toString().trim();
                    if (newRadioButton.isChecked() && name.length() == 0) {
                        nameEditText.requestFocus();
                        displayAlert(context, context.getString(R.string.dialog_new_row_name_alert));
                        return;
                    }
                    boolean currentRow = !newRadioButton.isChecked();
                    try {
                        BookmarkInfo bookmark = (BookmarkInfo) parent.getAdapter().getItem(position);
                        int rowId = 0;
                        int rowPosition = 0;
                        if (currentRow) {
                            rowId = context.getCurrentGalleryId();
                            ArrayList<ItemInfo> items = ItemsTable.getItems(context, rowId);
                            rowPosition = items.size(); // in last
                            // position
                            // for selected
                            // row
                        } else {
                            rowId = (int) RowsTable.insertRow(context, name, 0, RowInfo.FAVORITE_TYPE);
                            rowPosition = 0;
                        }
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(bookmark.getUrl()));

                        Uri uri = Uri.parse(bookmark.getUrl());
                        Log.d(LOG_TAG, "host=" + uri.getScheme() + "://" + uri.getHost());
                        String icon = Utils.getWebSiteIcon(context, "http://" + uri.getHost());
                        Log.d(LOG_TAG, "icon1=" + icon);
                        if (icon == null) {
                            // try base host address
                            int count = StringUtils.countMatches(uri.getHost(), ".");
                            if (count > 1) {
                                int index = uri.getHost().indexOf('.');
                                String baseHost = uri.getHost().substring(index + 1);
                                icon = Utils.getWebSiteIcon(context, "http://" + baseHost);
                                Log.d(LOG_TAG, "icon2=" + icon);
                            }
                        }

                        ItemsTable.insertItem(context, rowId, rowPosition, bookmark.getTitle(), intent, icon,
                                DatabaseHelper.SHORTCUT_TYPE);
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "displayAddBrowserBookmark", e);
                    }

                    // need to do this on UI thread
                    context.getHandler().post(new Runnable() {
                        public void run() {
                            context.showCover(false);
                            dialog.dismiss();
                            context.reloadAllGalleries();
                        }
                    });

                    if (currentRow) {
                        Analytics.logEvent(Analytics.ADD_BROWSER_BOOKMARK);
                    } else {
                        Analytics.logEvent(Analytics.ADD_BROWSER_BOOKMARK_WITH_ROW);
                    }

                }
            }).start();
        }
    });
    listView.setDrawingCacheEnabled(true);
    listView.setOnKeyListener(onKeyListener);
    dialog.setOnDismissListener(new OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            context.showCover(false);
        }

    });
    context.showCover(true);
    dialog.show();
    Analytics.logEvent(Analytics.DIALOG_ADD_BROWSER_BOOKMARK);
}

From source file:co.edu.uniajc.vtf.content.ListSitesFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_search:
        Dialog loDialog = this.createDialog();
        loDialog.setCanceledOnTouchOutside(false);
        loDialog.show();//from w w w  . j a  va2  s . co  m
        OptionsManager loOptions = new OptionsManager(this.getActivity());
        OptionsEntity loOptionsData = loOptions.getOptions();
        EditText loSearchControl = (EditText) loDialog.findViewById(R.id.txtSearch);
        loSearchControl.setText(loOptionsData.getSearch());
        break;
    case R.id.action_refresh:
        ListSitesFragment.this.cboForceUpdate = true;
        this.loadList(LoadActions.LOAD_DATA);
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.entertailion.android.launcher.Dialogs.java

/**
 * Display introduction to the user for first time launch
 * /*from  ww  w  .  j a v  a 2 s .  com*/
 * @param context
 */
public static void displayIntroduction(final Launcher context) {
    final Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.introduction);

    Typeface lightTypeface = ((LauncherApplication) context.getApplicationContext()).getLightTypeface(context);

    TextView titleTextView = (TextView) dialog.findViewById(R.id.intro_title);
    titleTextView.setTypeface(lightTypeface);
    TextView textView1 = (TextView) dialog.findViewById(R.id.intro_text1);
    textView1.setTypeface(lightTypeface);
    TextView textView2 = (TextView) dialog.findViewById(R.id.intro_text2);
    textView2.setTypeface(lightTypeface);

    ((Button) dialog.findViewById(R.id.intro_button)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            context.showCover(false);
            dialog.dismiss();
        }

    });
    dialog.setOnDismissListener(new OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            context.showCover(false);
        }

    });
    context.showCover(true);
    dialog.show();
    Analytics.logEvent(Analytics.DIALOG_INTRODUCTION);
}

From source file:com.zapto.park.ParkActivity.java

public boolean onOptionsItemSelected(MenuItem item) {
    Intent i = null;/* w  w  w  .java 2  s  .c o  m*/
    switch (item.getItemId()) {
    // Add User
    case 1:
        Dialog d = new Dialog(cActivity);
        final Dialog dialog = d;
        d.setContentView(R.layout.dialog_add_employee);
        d.setTitle(R.string.create_user_title);

        final EditText first_name = (EditText) d.findViewById(R.id.employee_first);
        final EditText last_name = (EditText) d.findViewById(R.id.employee_last);
        Button button_getinfo = (Button) d.findViewById(R.id.button_getinfo);

        button_getinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EmployeeDB edb = new EmployeeDB(context);

                String first = first_name.getText().toString();
                String last = last_name.getText().toString();

                ContentValues cv = new ContentValues();
                cv.put("totable_first", first);
                cv.put("totable_last", last);
                cv.put("totable_license", Globals.LICENSE_KEY);

                // Log request in database.
                ContentValues cv2 = new ContentValues();
                cv2.put("first", first);
                cv2.put("last", last);

                // Query database.
                edb.insertEmployee(cv2);

                // Close our database.
                edb.close();

                dialog.dismiss();
            }
        });

        d.show();

        break;
    // Settings
    case 2:
        Log.i(LOG_TAG, "Settings menu clicked.");
        i = new Intent(this, SettingsActivity.class);
        startActivity(i);
        break;
    case 3:
        Log.i(LOG_TAG, "View Log Loading.");
        i = new Intent(this, ListViewActivity.class);
        startActivity(i);
        break;
    case 4:
        doInit();
        Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                updateEmployees();
                doPendingRequests();
            }
        });
        break;
    case 5:
        Log.i(LOG_TAG, "SendEmailActivity Loading.");
        i = new Intent(this, SendEmailActivity.class);
        startActivity(i);
        break;
    case 6:
        Log.i(LOG_TAG, "View Log Loading.");
        i = new Intent(this, ListViewActivity.class);
        startActivity(i);
        break;
    }

    return true;
}

From source file:com.andrewshu.android.reddit.threads.ThreadsListActivity.java

public static void fillThreadClickDialog(Dialog dialog, ThingInfo thingInfo, RedditSettings settings,
        ThreadClickDialogOnClickListenerFactory threadClickDialogOnClickListenerFactory) {

    final CheckBox voteUpButton = (CheckBox) dialog.findViewById(R.id.vote_up_button);
    final CheckBox voteDownButton = (CheckBox) dialog.findViewById(R.id.vote_down_button);
    final TextView titleView = (TextView) dialog.findViewById(R.id.title);
    final TextView urlView = (TextView) dialog.findViewById(R.id.url);
    final TextView submissionStuffView = (TextView) dialog
            .findViewById(R.id.submissionTime_submitter_subreddit);
    final Button loginButton = (Button) dialog.findViewById(R.id.login_button);
    final Button linkButton = (Button) dialog.findViewById(R.id.thread_link_button);
    final Button commentsButton = (Button) dialog.findViewById(R.id.thread_comments_button);

    titleView.setText(thingInfo.getTitle());
    urlView.setText(thingInfo.getUrl());
    StringBuilder sb = new StringBuilder(Util.getTimeAgo(thingInfo.getCreated_utc())).append(" by ")
            .append(thingInfo.getAuthor()).append(" to ").append(thingInfo.getSubreddit());
    submissionStuffView.setText(sb);/* ww  w. j a v a2  s .c o m*/

    // Only show upvote/downvote if user is logged in
    if (settings.isLoggedIn()) {
        loginButton.setVisibility(View.GONE);
        voteUpButton.setVisibility(View.VISIBLE);
        voteDownButton.setVisibility(View.VISIBLE);

        // Remove the OnCheckedChangeListeners because we are about to setChecked(),
        // and I think the Buttons are recycled, so old listeners will fire
        // for the previous vote target ThingInfo.
        voteUpButton.setOnCheckedChangeListener(null);
        voteDownButton.setOnCheckedChangeListener(null);

        // Set initial states of the vote buttons based on user's past actions
        if (thingInfo.getLikes() == null) {
            // User is currently neutral
            voteUpButton.setChecked(false);
            voteDownButton.setChecked(false);
        } else if (thingInfo.getLikes() == true) {
            // User currenty likes it
            voteUpButton.setChecked(true);
            voteDownButton.setChecked(false);
        } else {
            // User currently dislikes it
            voteUpButton.setChecked(false);
            voteDownButton.setChecked(true);
        }
        voteUpButton.setOnCheckedChangeListener(
                threadClickDialogOnClickListenerFactory.getVoteUpOnCheckedChangeListener(thingInfo));
        voteDownButton.setOnCheckedChangeListener(
                threadClickDialogOnClickListenerFactory.getVoteDownOnCheckedChangeListener(thingInfo));
    } else {
        voteUpButton.setVisibility(View.GONE);
        voteDownButton.setVisibility(View.GONE);
        loginButton.setVisibility(View.VISIBLE);
        loginButton.setOnClickListener(threadClickDialogOnClickListenerFactory.getLoginOnClickListener());
    }

    // "link" button behaves differently for regular links vs. self posts and links to comments pages (e.g., bestof)
    if (thingInfo.isIs_self()) {
        // It's a self post. Both buttons do the same thing.
        linkButton.setEnabled(false);
    } else {
        linkButton.setOnClickListener(threadClickDialogOnClickListenerFactory.getLinkOnClickListener(thingInfo,
                settings.isUseExternalBrowser()));
        linkButton.setEnabled(true);
    }

    // "comments" button is easy: always does the same thing
    commentsButton
            .setOnClickListener(threadClickDialogOnClickListenerFactory.getCommentsOnClickListener(thingInfo));
}

From source file:com.digium.respoke.GroupListActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_join) {
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_join_group);
        dialog.setTitle("Join a group");

        Button dialogButton = (Button) dialog.findViewById(R.id.button1);
        TextView errorText = (TextView) dialog.findViewById(R.id.errorText);
        errorText.setText("");

        // if button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new View.OnClickListener() {
            @Override//from www.  ja  v  a2  s .  c om
            public void onClick(View v) {
                Button connectButton = (Button) dialog.findViewById(R.id.button1);
                ProgressBar progressCircle = (ProgressBar) dialog.findViewById(R.id.progress_circle);
                EditText userInput = (EditText) dialog.findViewById(R.id.editTextDialogUserInput);
                String groupID = userInput.getText().toString();

                if (groupID.length() > 0) {
                    TextView errorText = (TextView) dialog.findViewById(R.id.errorText);
                    errorText.setText("");
                    connectButton.setText("");
                    progressCircle.setVisibility(View.VISIBLE);

                    ContactManager.sharedInstance().joinGroup(groupID, new Respoke.TaskCompletionListener() {
                        @Override
                        public void onSuccess() {
                            dialog.dismiss();
                        }

                        @Override
                        public void onError(final String errorMessage) {
                            Button connectButton = (Button) dialog.findViewById(R.id.button1);
                            ProgressBar progressCircle = (ProgressBar) dialog
                                    .findViewById(R.id.progress_circle);
                            TextView errorText = (TextView) dialog.findViewById(R.id.errorText);

                            errorText.setText(errorMessage);
                            connectButton.setText("Connect");
                            progressCircle.setVisibility(View.INVISIBLE);
                        }
                    });
                } else {
                    TextView errorText = (TextView) dialog.findViewById(R.id.errorText);
                    errorText.setText("Group name may not be blank");
                }
            }
        });

        dialog.show();

        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.ibm.hellotodo.MainActivity.java

/**
 * Launches a dialog for adding a new TodoItem. Called when plus button is tapped.
 *
 * @param view The plus button that is tapped.
 *///www  . j a  va2  s.  c  o  m
public void addTodo(View view) {

    final Dialog addDialog = new Dialog(this);

    addDialog.setContentView(R.layout.add_edit_dialog);
    addDialog.setTitle("Add Todo");
    TextView textView = (TextView) addDialog.findViewById(android.R.id.title);
    if (textView != null) {
        textView.setGravity(Gravity.CENTER);
    }

    addDialog.setCancelable(true);
    Button add = (Button) addDialog.findViewById(R.id.Add);
    addDialog.show();

    // When done is pressed, send POST request to create TodoItem on Bluemix
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EditText itemToAdd = (EditText) addDialog.findViewById(R.id.todo);
            final String name = itemToAdd.getText().toString();
            // If text was added, continue with normal operations
            if (!name.isEmpty()) {

                // Create JSON for new TodoItem, id should be 0 for new items
                String json = "{\"text\":\"" + name + "\",\"isDone\":false,\"id\":0}";

                // Create POST request with IBM Mobile First SDK and set HTTP headers so Bluemix knows what to expect in the request
                Request request = new Request(client.getBluemixAppRoute() + "/api/Items", Request.POST);

                HashMap headers = new HashMap();
                List<String> cType = new ArrayList<>();
                cType.add("application/json");
                List<String> accept = new ArrayList<>();
                accept.add("Application/json");

                headers.put("Content-Type", cType);
                headers.put("Accept", accept);

                request.setHeaders(headers);

                request.send(getApplicationContext(), json, new ResponseListener() {
                    // On success, update local list with new TodoItem
                    @Override
                    public void onSuccess(Response response) {
                        Log.i(TAG, "Item created successfully");

                        loadList();
                    }

                    // On failure, log errors
                    @Override
                    public void onFailure(Response response, Throwable t, JSONObject extendedInfo) {
                        String errorMessage = "";

                        if (response != null) {
                            errorMessage += response.toString() + "\n";
                        }

                        if (t != null) {
                            StringWriter sw = new StringWriter();
                            PrintWriter pw = new PrintWriter(sw);
                            t.printStackTrace(pw);
                            errorMessage += "THROWN" + sw.toString() + "\n";
                        }

                        if (extendedInfo != null) {
                            errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
                        }

                        if (errorMessage.isEmpty())
                            errorMessage = "Request Failed With Unknown Error.";

                        Log.e(TAG, "addTodo failed with error: " + errorMessage);
                    }
                });
            }

            // Kill dialog when finished, or if no text was added
            addDialog.dismiss();
        }
    });
}

From source file:com.example.google.playservices.placepicker.PlacePickerFragment.java

@Override
public void onCardClick(int cardActionId, String cardTag) {
    if (cardActionId == ACTION_PICK_PLACE) {
        // BEGIN_INCLUDE(intent)
        /* Use the PlacePicker Builder to construct an Intent.
        Note: This sample demonstrates a basic use case.
        The PlacePicker Builder supports additional properties such as search bounds.
         *//* www.ja  v a 2s.  c  o m*/
        try {
            PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder();
            Intent intent = intentBuilder.build(getActivity());
            // Start the Intent by requesting a result, identified by a request code.
            startActivityForResult(intent, REQUEST_PLACE_PICKER);

            // Hide the pick option in the UI to prevent users from starting the picker
            // multiple times.
            showPickAction(false);

        } catch (GooglePlayServicesRepairableException e) {
            GooglePlayServicesUtil.getErrorDialog(e.getConnectionStatusCode(), getActivity(), 0);
        } catch (GooglePlayServicesNotAvailableException e) {
            Toast.makeText(getActivity(), "Google Play Services is not available.", Toast.LENGTH_LONG).show();
        }

        // END_INCLUDE(intent)
    } else if (cardActionId == ACTION_REPORT_WAIT) {
        final Dialog dialog = new Dialog(this.getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.report);

        final NumberPicker np = (NumberPicker) dialog.findViewById(R.id.numpicker);
        np.setMaxValue(120);
        np.setMinValue(0);

        // Report
        Button dialogButtonReport = (Button) dialog.findViewById(R.id.dialogButtonReport);
        dialogButtonReport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HttpPost httppost = new HttpPost("http://powergrid.xyz/quickq/restaurantpost.php");
                httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
                List<NameValuePair> nameValuePairs = new ArrayList<>(2);
                // TODO
                nameValuePairs.add(new BasicNameValuePair("placeid", globalplace.getId()));
                nameValuePairs.add(new BasicNameValuePair("waittime", String.valueOf(np.getValue())));
                try {
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                powergridServerReportTime task = new powergridServerReportTime();
                task.execute(httppost);

                dialog.dismiss();
            }
        });

        // Cancel
        Button dialogButtonCancel = (Button) dialog.findViewById(R.id.dialogButtonCancel);
        // If button is clicked, close the custom dialog
        dialogButtonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }
}