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:com.example.zf_android.activity.MerchantEdit.java

private void show2Dialog(int type) {

    AlertDialog.Builder builder = new AlertDialog.Builder(MerchantEdit.this);
    final String[] items = getResources().getStringArray(R.array.apply_detail_upload);

    MerchantEdit.this.type = type;

    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override// w w  w .j a va  2  s .  c  om
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {

            case 0: {

                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                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(MerchantEdit.this, getString(R.string.toast_no_sdcard));
                }
                break;
            }
            }
        }
    });

    builder.show();
}

From source file:com.mediaexplorer.remote.MexRemoteActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from   w ww  .ja v  a  2s .  c  om*/

    this.setTitle(R.string.app_name);
    dbg = "MexWebremote";

    text_view = (TextView) findViewById(R.id.text);

    web_view = (WebView) findViewById(R.id.link_view);
    web_view.getSettings().setJavaScriptEnabled(true);/*
                                                      /* Future: setOverScrollMode is API level >8
                                                      * web_view.setOverScrollMode (OVER_SCROLL_NEVER);
                                                      */

    web_view.setBackgroundColor(0);

    web_view.setWebViewClient(new WebViewClient() {
        /* for some reason we only get critical errors so an auth error
         * is not handled here which is why there is some crack that test
         * the connection with a special httpclient
         */
        @Override
        public void onReceivedHttpAuthRequest(final WebView view, final HttpAuthHandler handler,
                final String host, final String realm) {
            String[] userpass = new String[2];

            userpass = view.getHttpAuthUsernamePassword(host, realm);

            HttpResponse response = null;
            HttpGet httpget;
            DefaultHttpClient httpclient;
            String target_host;
            int target_port;

            target_host = MexRemoteActivity.this.target_host;
            target_port = MexRemoteActivity.this.target_port;

            /* We may get null from getHttpAuthUsernamePassword which will
             * break the setCredentials so junk used instead to keep
             * it happy.
             */

            Log.d(dbg, "using the set httpauth, testing auth using client");
            try {
                if (userpass == null) {
                    userpass = new String[2];
                    userpass[0] = "none";
                    userpass[1] = "none";
                }
            } catch (Exception e) {
                userpass = new String[2];
                userpass[0] = "none";
                userpass[1] = "none";
            }

            /* Log.d ("debug",
             *  "trying: GET http://"+userpass[0]+":"+userpass[1]+"@"+target_host+":"+target_port+"/");
             */
            /* We're going to test the authentication credentials that we
             * have before using them so that we can act on the response.
             */

            httpclient = new DefaultHttpClient();

            httpget = new HttpGet("http://" + target_host + ":" + target_port + "/");

            httpclient.getCredentialsProvider().setCredentials(new AuthScope(target_host, target_port),
                    new UsernamePasswordCredentials(userpass[0], userpass[1]));

            try {
                response = httpclient.execute(httpget);
            } catch (IOException e) {
                Log.d(dbg, "Problem executing the http get");
                e.printStackTrace();
            }

            Log.d(dbg, "HTTP reponse:" + Integer.toString(response.getStatusLine().getStatusCode()));
            if (response.getStatusLine().getStatusCode() == 401) {
                /* We got Authentication failed (401) so ask user for u/p */

                /* login dialog box */
                final AlertDialog.Builder logindialog;
                final EditText user;
                final EditText pass;

                LinearLayout layout;
                LayoutParams params;

                TextView label_username;
                TextView label_password;

                logindialog = new AlertDialog.Builder(MexRemoteActivity.this);

                logindialog.setTitle("Mex Webremote login");

                user = new EditText(MexRemoteActivity.this);
                pass = new EditText(MexRemoteActivity.this);

                layout = new LinearLayout(MexRemoteActivity.this);

                pass.setTransformationMethod(new PasswordTransformationMethod());

                layout.setOrientation(LinearLayout.VERTICAL);

                params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

                layout.setLayoutParams(params);
                user.setLayoutParams(params);
                pass.setLayoutParams(params);

                label_username = new TextView(MexRemoteActivity.this);
                label_password = new TextView(MexRemoteActivity.this);

                label_username.setText("Username:");
                label_password.setText("Password:");

                layout.addView(label_username);
                layout.addView(user);
                layout.addView(label_password);
                layout.addView(pass);
                logindialog.setView(layout);

                logindialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });

                logindialog.setPositiveButton("Login", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String uvalue = user.getText().toString().trim();
                        String pvalue = pass.getText().toString().trim();
                        view.setHttpAuthUsernamePassword(host, realm, uvalue, pvalue);

                        handler.proceed(uvalue, pvalue);
                    }
                });
                logindialog.show();
                /* End login dialog box */
            } else /* We didn't get a 401 */
            {
                handler.proceed(userpass[0], userpass[1]);
            }
        } /* End onReceivedHttpAuthRequest */
    }); /* End Override */

    /* Run mdns to check for service in a "runnable" (async) */
    handler.post(new Runnable() {
        public void run() {
            startMdns();
        }
    });

    dialog = ProgressDialog.show(MexRemoteActivity.this, "", "Searching...", true);

    /* Let's put something in the webview while we're waiting */
    String summary = "<html><head><style>body { background-color: #000000; color: #ffffff; }></style></head><body><p>Searching for the media explorer webservice</p><p>More infomation on <a href=\"http://media-explorer.github.com\" >Media Explorer's home page</a></p></body></html>";
    web_view.loadData(summary, "text/html", "utf-8");

}

From source file:com.speed.traquer.app.TraqComplaintTaxi.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_traq_complaint_taxi);
    easyTracker = EasyTracker.getInstance(TraqComplaintTaxi.this);
    //onCreateView(savedInstanceState);
    //InitialSetupUI();

    //Added UIHelper
    uiHelper = new UiLifecycleHelper(this, null);
    uiHelper.onCreate(savedInstanceState);

    inputTaxi = (EditText) findViewById(R.id.taxi_id);
    taxiDriver = (EditText) findViewById(R.id.taxi_driver);
    taxiLic = (EditText) findViewById(R.id.taxi_license);
    geoLat = (TextView) findViewById(R.id.geoLat);
    geoLong = (TextView) findViewById(R.id.geoLong);
    editDate = (EditText) findViewById(R.id.editDate);
    editTime = (EditText) findViewById(R.id.editTime);
    editCurrTime = (EditText) findViewById(R.id.editCurrTime);
    complainSend = (Button) findViewById(R.id.complain_send);

    ProgressBar barProgress = (ProgressBar) findViewById(R.id.progressLoading);
    ProgressBar barProgressFrom = (ProgressBar) findViewById(R.id.progressLoadingFrom);
    ProgressBar barProgressTo = (ProgressBar) findViewById(R.id.progressLoadingTo);

    actv_comp_taxi = (AutoCompleteTextView) findViewById(R.id.search_taxi_comp);
    SuggestionAdapter sa = new SuggestionAdapter(this, actv_comp_taxi.getText().toString(), taxiUrl,
            "compcode");
    sa.setLoadingIndicator(barProgress);
    actv_comp_taxi.setAdapter(sa);//from   w  w  w .  j a  v a2 s.  c o m

    actv_from = (AutoCompleteTextView) findViewById(R.id.search_from);
    SuggestionAdapter saFrom = new SuggestionAdapter(this, actv_from.getText().toString(), locUrl, "location");
    saFrom.setLoadingIndicator(barProgressFrom);
    actv_from.setAdapter(saFrom);

    actv_to = (AutoCompleteTextView) findViewById(R.id.search_to);
    SuggestionAdapter saTo = new SuggestionAdapter(this, actv_to.getText().toString(), locUrl, "location");
    saTo.setLoadingIndicator(barProgressTo);
    actv_to.setAdapter(saTo);

    /*if(isNetworkConnected()) {
    new getTaxiComp().execute(new ApiConnector());
    }*/

    //Setting Fonts
    String fontPath = "fonts/segoeuil.ttf";
    Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
    complainSend.setTypeface(tf);
    inputTaxi.setTypeface(tf);
    editDate.setTypeface(tf);
    editTime.setTypeface(tf);
    actv_comp_taxi.setTypeface(tf);
    actv_to.setTypeface(tf);
    actv_from.setTypeface(tf);
    taxiDriver.setTypeface(tf);
    taxiLic.setTypeface(tf);

    TextView txtComp = (TextView) findViewById(R.id.taxi_comp);
    txtComp.setTypeface(tf);

    TextView txtTaxiDriver = (TextView) findViewById(R.id.txt_taxi_driver);
    txtTaxiDriver.setTypeface(tf);

    TextView txtTaxiLic = (TextView) findViewById(R.id.txt_taxi_license);
    txtTaxiLic.setTypeface(tf);

    TextView txtNumber = (TextView) findViewById(R.id.taxi_number);
    txtNumber.setTypeface(tf);

    TextView txtTo = (TextView) findViewById(R.id.to);
    txtTo.setTypeface(tf);

    TextView txtDate = (TextView) findViewById(R.id.date);
    txtDate.setTypeface(tf);

    TextView txtTime = (TextView) findViewById(R.id.time);
    txtTime.setTypeface(tf);

    gLongitude = this.getIntent().getExtras().getDouble("Longitude");
    gLatitude = this.getIntent().getExtras().getDouble("Latitude");
    speedTaxiExceed = this.getIntent().getExtras().getDouble("SpeedTaxiExceed");

    isTwitterSelected = false;
    isFacebookSelected = false;
    isDefaultSelected = false;
    isSmsSelected = false;

    geoLat.setText(Double.toString(gLatitude));
    geoLong.setText(Double.toString(gLongitude));

    rateBtnBus = (ImageButton) findViewById(R.id.btn_rate_bus);

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

            if (actv_comp_taxi.length() != 0) {
                final AlertDialog.Builder alertBox = new AlertDialog.Builder(TraqComplaintTaxi.this);
                alertBox.setIcon(R.drawable.info_icon);
                alertBox.setCancelable(false);
                alertBox.setTitle("Do you want to cancel complaint?");
                alertBox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        // finish used for destroyed activity
                        easyTracker.send(MapBuilder
                                .createEvent("Complaint", "Cancel Complaint (Yes)", "Complaint event", null)
                                .build());
                        finish();
                    }
                });

                alertBox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        easyTracker.send(MapBuilder
                                .createEvent("Complaint", "Cancel Complaint (No)", "Complaint event", null)
                                .build());
                        dialog.cancel();
                    }
                });

                alertBox.show();
            } else {
                Intent intent = new Intent(getApplicationContext(), TraqComplaint.class);
                intent.putExtra("Latitude", gLatitude);
                intent.putExtra("Longitude", gLongitude);
                intent.putExtra("SpeedBusExceed", speedTaxiExceed);
                startActivity(intent);
            }
        }
    });

    complainSend.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            String taxi_id = inputTaxi.getText().toString().toUpperCase();
            String taxi_comp = actv_comp_taxi.getText().toString();

            /*if(taxi_comp.length() == 0){
            Toast.makeText(TraqComplaintTaxi.this, "Taxi Company is required!", Toast.LENGTH_SHORT).show();
            }else */
            if (taxi_comp.length() < 2) {
                Toast.makeText(TraqComplaintTaxi.this, "Invalid Taxi Company.", Toast.LENGTH_SHORT).show();
            } else if (taxi_id.length() == 0) {
                Toast.makeText(TraqComplaintTaxi.this, "Taxi Plate Number is required!", Toast.LENGTH_SHORT)
                        .show();
            } else if (taxi_id.length() < 7) {
                Toast.makeText(TraqComplaintTaxi.this, "Invalid Taxi Number.", Toast.LENGTH_SHORT).show();
            } else {
                easyTracker.send(
                        MapBuilder.createEvent("Complaint", "Dialog Prompt", "Complaint event", null).build());
                PromptCustomDialog();
            }
        }
    });
    setCurrentDateOnView();
    getCurrentTime();

    //Shi Chuan's Code

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(TraqComplaintTaxi.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Check if twitter keys are set
    if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) {
        // Internet Connection is not present
        alert.showAlertDialog(TraqComplaintTaxi.this, "Twitter oAuth tokens",
                "Please set your twitter oauth tokens first!", false);
        // stop executing code by return
        return;
    }

    // Shared Preferences
    mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

    /** This if conditions is tested once is
     * redirected from twitter page. Parse the uri to get oAuth
     * Verifier
     * */

    if (!isTwitterLoggedInAlready()) {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
            // oAuth verifier
            String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

            try {
                // Get the access token
                AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

                // Shared Preferences
                SharedPreferences.Editor e = mSharedPreferences.edit();

                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes

                Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

                // Getting user details from twitter
                // For now i am getting his name only
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);

                String username = user.getName();
                String description = user.getDescription();

                // Displaying in xml ui
                //lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>" + description));
            } catch (Exception e) {
                // Check log for login errors
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }
    }

    //LocationManager lm = (LocationManager)  this.getSystemService(Context.LOCATION_SERVICE);
    //LocationListener ll = new passengerLocationListener();
    //lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);

}

From source file:za.co.neilson.alarm.preferences.AlarmPreferencesActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // requestWindowFeature(Window.FEATURE_NO_TITLE);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.alarm_preferences);

    pref = getSharedPreferences("AppPref", MODE_PRIVATE);
    email = getIntent().getStringExtra("email");
    Log.d("? ???!!! ", "" + email);

    Bundle bundle = getIntent().getExtras();
    if (bundle != null && bundle.containsKey("alarm")) {
        setMathAlarm((Alarm) bundle.getSerializable("alarm"));
    } else {//w w w .ja  v  a 2s .c o m
        setMathAlarm(new Alarm());
    }
    if (bundle != null && bundle.containsKey("adapter")) {
        setListAdapter((AlarmPreferenceListAdapter) bundle.getSerializable("adapter"));
    } else {
        setListAdapter(new AlarmPreferenceListAdapter(this, getMathAlarm()));
    }

    getListView().setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> l, View v, int position, long id) {
            final AlarmPreferenceListAdapter alarmPreferenceListAdapter = (AlarmPreferenceListAdapter) getListAdapter();
            final AlarmPreference alarmPreference = (AlarmPreference) alarmPreferenceListAdapter
                    .getItem(position);

            AlertDialog.Builder alert;
            v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
            switch (alarmPreference.getType()) {
            case BOOLEAN:
                CheckedTextView checkedTextView = (CheckedTextView) v;
                boolean checked = !checkedTextView.isChecked();
                ((CheckedTextView) v).setChecked(checked);
                switch (alarmPreference.getKey()) {
                case ALARM_ACTIVE:
                    alarm.setAlarmActive(checked);
                    break;
                case ALARM_VIBRATE:
                    alarm.setVibrate(checked);
                    if (checked) {
                        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                        vibrator.vibrate(1000);
                    }
                    break;
                }
                alarmPreference.setValue(checked);
                break;
            case STRING:

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

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                // Set an EditText view to get user input
                final EditText input = new EditText(AlarmPreferencesActivity.this);

                input.setText(alarmPreference.getValue().toString());

                alert.setView(input);
                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        alarmPreference.setValue(input.getText().toString());

                        if (alarmPreference.getKey() == Key.ALARM_NAME) {
                            alarm.setAlarmName(alarmPreference.getValue().toString());
                        }

                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();
                    }
                });
                alert.show();
                break;
            case LIST:
                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                CharSequence[] items = new CharSequence[alarmPreference.getOptions().length];
                for (int i = 0; i < items.length; i++)
                    items[i] = alarmPreference.getOptions()[i];

                alert.setItems(items, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (alarmPreference.getKey()) {
                        case ALARM_DIFFICULTY:
                            Alarm.Difficulty d = Alarm.Difficulty.values()[which];
                            alarm.setDifficulty(d);
                            break;
                        case ALARM_TONE:
                            alarm.setAlarmTonePath(alarmPreferenceListAdapter.getAlarmTonePaths()[which]);
                            if (alarm.getAlarmTonePath() != null) {
                                if (mediaPlayer == null) {
                                    mediaPlayer = new MediaPlayer();
                                } else {
                                    if (mediaPlayer.isPlaying())
                                        mediaPlayer.stop();
                                    mediaPlayer.reset();
                                }
                                try {
                                    // mediaPlayer.setVolume(1.0f, 1.0f);
                                    mediaPlayer.setVolume(0.2f, 0.2f);
                                    mediaPlayer.setDataSource(AlarmPreferencesActivity.this,
                                            Uri.parse(alarm.getAlarmTonePath()));
                                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                                    mediaPlayer.setLooping(false);
                                    mediaPlayer.prepare();
                                    mediaPlayer.start();

                                    // Force the mediaPlayer to stop after 3
                                    // seconds...
                                    if (alarmToneTimer != null)
                                        alarmToneTimer.cancel();
                                    alarmToneTimer = new CountDownTimer(3000, 3000) {
                                        @Override
                                        public void onTick(long millisUntilFinished) {

                                        }

                                        @Override
                                        public void onFinish() {
                                            try {
                                                if (mediaPlayer.isPlaying())
                                                    mediaPlayer.stop();
                                            } catch (Exception e) {

                                            }
                                        }
                                    };
                                    alarmToneTimer.start();
                                } catch (Exception e) {
                                    try {
                                        if (mediaPlayer.isPlaying())
                                            mediaPlayer.stop();
                                    } catch (Exception e2) {

                                    }
                                }
                            }
                            break;
                        default:
                            break;
                        }
                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();
                    }

                });

                alert.show();
                break;
            case MULTIPLE_LIST:
                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                CharSequence[] multiListItems = new CharSequence[alarmPreference.getOptions().length];
                for (int i = 0; i < multiListItems.length; i++)
                    multiListItems[i] = alarmPreference.getOptions()[i];

                boolean[] checkedItems = new boolean[multiListItems.length];
                for (Alarm.Day day : getMathAlarm().getDays()) {
                    checkedItems[day.ordinal()] = true;
                }
                alert.setMultiChoiceItems(multiListItems, checkedItems, new OnMultiChoiceClickListener() {

                    @Override
                    public void onClick(final DialogInterface dialog, int which, boolean isChecked) {

                        Alarm.Day thisDay = Alarm.Day.values()[which];

                        if (isChecked) {
                            alarm.addDay(thisDay);
                        } else {
                            // Only remove the day if there are more than 1
                            // selected
                            if (alarm.getDays().length > 1) {
                                alarm.removeDay(thisDay);
                            } else {
                                // If the last day was unchecked, re-check
                                // it
                                ((AlertDialog) dialog).getListView().setItemChecked(which, true);
                            }
                        }

                    }
                });
                alert.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();

                    }
                });
                alert.show();
                break;
            case TIME:
                TimePickerDialog timePickerDialog = new TimePickerDialog(AlarmPreferencesActivity.this,
                        new OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker timePicker, int hours, int minutes) {
                                Calendar newAlarmTime = Calendar.getInstance();
                                newAlarmTime.set(Calendar.HOUR_OF_DAY, hours);
                                newAlarmTime.set(Calendar.MINUTE, minutes);
                                newAlarmTime.set(Calendar.SECOND, 0);
                                alarm.setAlarmTime(newAlarmTime);
                                alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                                alarmPreferenceListAdapter.notifyDataSetChanged();
                            }
                        }, alarm.getAlarmTime().get(Calendar.HOUR_OF_DAY),
                        alarm.getAlarmTime().get(Calendar.MINUTE), true);
                timePickerDialog.setTitle(alarmPreference.getTitle());
                timePickerDialog.show();
            default:
                break;
            }
        }
    });
}

From source file:com.t2.compassionMeditation.DeviceManagerActivity.java

/**
 * Handles UI button clicks/*w  w  w. j a va  2 s.co  m*/
 * @param v
 */
public void onButtonClick(final View v) {
    final int id = v.getId();
    switch (id) {

    // Present a list of all parameter types to allow the user
    // to associate a specific device (address) to a specific parameter
    // This association will be used in the main activities so that they
    // know the BT address of particular sensors to tell them to start/stop

    // The associations are stored in Shared pref
    //   key = param name (See R.array.parameter_names)
    //   value = BT address

    case R.id.parameter:
        final String address = (String) v.getTag();
        AlertDialog.Builder alertParamChooser = new AlertDialog.Builder(mInstance);
        alertParamChooser.setTitle("Select parameter for this device");
        //             mParamChooserAlert = alertParamChooser.create();

        alertParamChooser.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            }
        });
        alertParamChooser.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            }
        });
        alertParamChooser.setSingleChoiceItems(R.array.parameter_names, -1,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names);
                        final String name = paramNamesStringArray[which];

                        // See which pamrameter is associated with this name
                        String device = SharedPref.getDeviceForParam(mInstance, name);
                        if (device != null && which != 0) {
                            AlertDialog.Builder alertWarning = new AlertDialog.Builder(mInstance);
                            String message = String.format(
                                    "Another sensor (%s) currently feeds this parameter. Please change this previous mapping before trying again",
                                    device);
                            alertWarning.setMessage(message);

                            alertWarning.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    mParamChooserAlert.dismiss();
                                }

                            });
                            alertWarning.setNegativeButton("Select Anyway",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int whichButton) {
                                            Log.d(TAG, "param name = " + name + ", address = " + address);
                                            if (which != 0) {
                                                SharedPref.setParamForDevice(mInstance, name, address);
                                                v.getBackground().setColorFilter(Color.GREEN,
                                                        PorterDuff.Mode.MULTIPLY);
                                                ((Button) v.findViewById(R.id.parameter)).setText(name);
                                            } else {
                                                SharedPref.setParamForDevice(mInstance, name, address);
                                                v.getBackground().setColorFilter(Color.LTGRAY,
                                                        PorterDuff.Mode.MULTIPLY);
                                                ((Button) v.findViewById(R.id.parameter)).setText("Parameter");

                                            }

                                        }

                                    });

                            alertWarning.show();

                        } else {
                            // The parameter is currently not mapped to a sensor, so we can go ahead and map it
                            Log.d(TAG, "param name = " + name + ", address = " + address);
                            if (which != 0) {
                                SharedPref.setParamForDevice(mInstance, name, address);
                                v.getBackground().setColorFilter(Color.GREEN, PorterDuff.Mode.MULTIPLY);
                                ((Button) v.findViewById(R.id.parameter)).setText(name);
                            } else {
                                SharedPref.setParamForDevice(mInstance, name, address);
                                v.getBackground().setColorFilter(Color.LTGRAY, PorterDuff.Mode.MULTIPLY);
                                ((Button) v.findViewById(R.id.parameter)).setText("Parameter");

                            }
                        }
                    }
                });
        //            alert.show();   
        mParamChooserAlert = alertParamChooser.create();

        mParamChooserAlert.show();

        break;

    }
}

From source file:com.getkickbak.plugin.NotificationPlugin.java

/**
 * Builds and shows a native Android confirm dialog with given title, message, buttons.
 * This dialog only shows up to 3 buttons. Any labels after that will be ignored.
 * The index of the button pressed will be returned to the JavaScript callback identified by callbackId.
 * // w  ww. jav  a2s  .c om
 * @param message
 *           The message the dialog should display
 * @param title
 *           The title of the dialog
 * @param buttonLabels
 *           A comma separated list of button labels (Up to 3 buttons)
 * @param callbackContext
 *           The callback context.
 */
public synchronized void confirm(final String message, final String title, String buttonLabels,
        final CallbackContext callbackContext) {

    final NotificationPlugin notification = this;
    final CordovaInterface cordova = this.cordova;
    final String[] fButtons = (buttonLabels != null) ? buttonLabels.split(",") : new String[0];

    Runnable runnable = new Runnable() {
        public void run() {
            AlertDialog.Builder dlg = new AlertDialog.Builder(cordova.getActivity());
            dlg.setMessage(message);
            dlg.setTitle(title);
            dlg.setCancelable((fButtons.length > 0) ? true : false);

            // First button
            if (fButtons.length > 0) {
                dlg.setNegativeButton(fButtons[0], new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        notification.dismiss(-1, dialog);
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1));
                    }
                });
                dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
                    public void onCancel(DialogInterface dialog) {
                        notification.dismiss(-1, dialog);
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
                    }
                });
            }

            // Second button
            if (fButtons.length > 1) {
                dlg.setNeutralButton(fButtons[1], new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        notification.dismiss(-1, dialog);
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2));
                    }
                });
            }

            // Third button
            if (fButtons.length > 2) {
                dlg.setPositiveButton(fButtons[2], new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        notification.dismiss(-1, dialog);
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3));
                    }
                });
            }
            /*
             * dlg.setOnDismissListener(new AlertDialog.OnDismissListener()
             * {
             * public void onDismiss(DialogInterface dialog)
             * {
             * }
             * });
             */

            dlg.create();
            Integer key = Integer.valueOf(((int) (Math.random() * 10000000)) + 10000);
            AlertDialog value = dlg.show();

            notification.dialogsIA.put(key, value);
            notification.dialogsAI.put(value, key);
            if (fButtons.length == 0) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, key.intValue()));
            }
        };
    };
    this.cordova.getActivity().runOnUiThread(runnable);
}

From source file:adventure_fragments.Camping.java

public void AddItemNow() {
    final EditText input;

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Add item to list");
    input = new EditText(getActivity());
    int maxLength = 20;
    input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxLength) });

    builder.setView(input);//from   www  . jav a2s.  c  o  m
    builder.setPositiveButton("Add item", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String item_name = input.getText().toString();

            if (item_name.equals("")) {
                Toast.makeText(getActivity(), "Please enter a name for the item", Toast.LENGTH_SHORT).show();
            } else if (item_name.equals(" ")) {
                Toast.makeText(getActivity(), "Please enter a name for the item", Toast.LENGTH_SHORT).show();
            } else if (item_name.equals("  ")) {
                Toast.makeText(getActivity(), "Please enter a name for the item", Toast.LENGTH_SHORT).show();
            } else if (item_name.equals("This app sucks")) {
                Toast.makeText(getActivity(), "No it doesn't!", Toast.LENGTH_SHORT).show();
            } else {

                ItemClass itemClass = new ItemClass(item_name, 0);
                db.addItemCamping(itemClass);
                adapt.add(itemClass);
                adapt.notifyDataSetChanged();
                list = db.getAllItemsCamping();
                adapt = new CustomAdapter1(getActivity(), R.layout.item_layout, list);
                listItem = (ListView) getActivity().findViewById(R.id.listview_camp);
                listItem.setAdapter(adapt);
                count = listItem.getCount();
                if (count > 0) {
                    nothingtext.setVisibility(View.GONE);
                } else if (count == 0) {
                    nothingtext.setVisibility(View.VISIBLE);
                }

            }
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            list = db.getAllItemsCamping();
            adapt = new CustomAdapter1(getActivity(), R.layout.item_layout, list);
            listItem = (ListView) getActivity().findViewById(R.id.listview_camp);
            listItem.setAdapter(adapt);

            dialog.dismiss();
        }
    });

    builder.show();
}

From source file:adventure_fragments.Climbing.java

public void AddItemNow() {
    final EditText input;

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Add item to list");
    input = new EditText(getActivity());
    int maxLength = 20;
    input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxLength) });

    builder.setView(input);/*from ww  w. j a va  2s  . co m*/
    builder.setPositiveButton("Add item", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String item_name = input.getText().toString();

            if (item_name.equals("")) {
                Toast.makeText(getActivity(), "Please enter a name for the item", Toast.LENGTH_SHORT).show();
            } else if (item_name.equals(" ")) {
                Toast.makeText(getActivity(), "Please enter a name for the item", Toast.LENGTH_SHORT).show();
            } else if (item_name.equals("  ")) {
                Toast.makeText(getActivity(), "Please enter a name for the item", Toast.LENGTH_SHORT).show();
            } else if (item_name.equals("This app sucks")) {
                Toast.makeText(getActivity(), "No it doesn't!", Toast.LENGTH_SHORT).show();
            } else {

                ItemClass itemClass = new ItemClass(item_name, 0);
                db.addItemClimbing(itemClass);
                adapt.add(itemClass);
                adapt.notifyDataSetChanged();
                list = db.getAllItemsClimbing();
                adapt = new CustomAdapter1(getActivity(), R.layout.item_layout, list);
                listItem = (ListView) getActivity().findViewById(R.id.listview_climb);
                listItem.setAdapter(adapt);
                count = listItem.getCount();
                if (count > 0) {
                    nothingtext.setVisibility(View.GONE);
                } else if (count == 0) {
                    nothingtext.setVisibility(View.VISIBLE);
                }

            }
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            list = db.getAllItemsClimbing();
            adapt = new CustomAdapter1(getActivity(), R.layout.item_layout, list);
            listItem = (ListView) getActivity().findViewById(R.id.listview_climb);
            listItem.setAdapter(adapt);

            dialog.dismiss();
        }
    });

    builder.show();
}

From source file:com.carlrice.reader.activity.EditFeedActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        finish();/*from w w  w  .j av  a  2s  .  c  om*/
        return true;
    case R.id.menu_add_filter: {
        final View dialogView = getLayoutInflater().inflate(R.layout.dialog_filter_edit, null);

        new AlertDialog.Builder(this) //
                .setTitle(R.string.filter_add_title) //
                .setView(dialogView) //
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        String filterText = ((EditText) dialogView.findViewById(R.id.filterText)).getText()
                                .toString();
                        if (filterText.length() != 0) {
                            String feedId = getIntent().getData().getLastPathSegment();

                            ContentValues values = new ContentValues();
                            values.put(FilterColumns.FILTER_TEXT, filterText);
                            values.put(FilterColumns.IS_REGEX,
                                    ((CheckBox) dialogView.findViewById(R.id.regexCheckBox)).isChecked());
                            values.put(FilterColumns.IS_APPLIED_TO_TITLE,
                                    ((RadioButton) dialogView.findViewById(R.id.applyTitleRadio)).isChecked());
                            values.put(FilterColumns.IS_ACCEPT_RULE,
                                    ((RadioButton) dialogView.findViewById(R.id.acceptRadio)).isChecked());

                            ContentResolver cr = getContentResolver();
                            cr.insert(FilterColumns.FILTERS_FOR_FEED_CONTENT_URI(feedId), values);
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                    }
                }).show();
        return true;
    }
    case R.id.menu_search_feed: {
        final View dialogView = getLayoutInflater().inflate(R.layout.dialog_search_feed, null);
        final EditText searchText = (EditText) dialogView.findViewById(R.id.searchText);
        if (!mUrlEditText.getText().toString().startsWith(Constants.HTTP_SCHEME)
                && !mUrlEditText.getText().toString().startsWith(Constants.HTTPS_SCHEME)) {
            searchText.setText(mUrlEditText.getText());
        }
        final RadioGroup radioGroup = (RadioGroup) dialogView.findViewById(R.id.radioGroup);

        new AlertDialog.Builder(EditFeedActivity.this) //
                .setIcon(R.drawable.action_search) //
                .setTitle(R.string.feed_search) //
                .setView(dialogView) //
                .setPositiveButton(android.R.string.search_go, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (searchText.getText().length() > 0) {
                            String tmp = searchText.getText().toString();
                            try {
                                tmp = URLEncoder.encode(searchText.getText().toString(), Constants.UTF8);
                            } catch (UnsupportedEncodingException ignored) {
                            }
                            final String text = tmp;

                            switch (radioGroup.getCheckedRadioButtonId()) {
                            case R.id.byWebSearch:
                                final ProgressDialog pd = new ProgressDialog(EditFeedActivity.this);
                                pd.setMessage(getString(R.string.loading));
                                pd.setCancelable(true);
                                pd.setIndeterminate(true);
                                pd.show();

                                getLoaderManager().restartLoader(1, null,
                                        new LoaderManager.LoaderCallbacks<ArrayList<HashMap<String, String>>>() {

                                            @Override
                                            public Loader<ArrayList<HashMap<String, String>>> onCreateLoader(
                                                    int id, Bundle args) {
                                                return new GetFeedSearchResultsLoader(EditFeedActivity.this,
                                                        text);
                                            }

                                            @Override
                                            public void onLoadFinished(
                                                    Loader<ArrayList<HashMap<String, String>>> loader,
                                                    final ArrayList<HashMap<String, String>> data) {
                                                pd.cancel();

                                                if (data == null) {
                                                    Toast.makeText(EditFeedActivity.this, R.string.error,
                                                            Toast.LENGTH_SHORT).show();
                                                } else if (data.isEmpty()) {
                                                    Toast.makeText(EditFeedActivity.this, R.string.no_result,
                                                            Toast.LENGTH_SHORT).show();
                                                } else {
                                                    AlertDialog.Builder builder = new AlertDialog.Builder(
                                                            EditFeedActivity.this);
                                                    builder.setTitle(R.string.feed_search);

                                                    // create the grid item mapping
                                                    String[] from = new String[] { FEED_SEARCH_TITLE,
                                                            FEED_SEARCH_DESC };
                                                    int[] to = new int[] { android.R.id.text1,
                                                            android.R.id.text2 };

                                                    // fill in the grid_item layout
                                                    SimpleAdapter adapter = new SimpleAdapter(
                                                            EditFeedActivity.this, data,
                                                            R.layout.item_search_result, from, to);
                                                    builder.setAdapter(adapter,
                                                            new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog,
                                                                        int which) {
                                                                    mNameEditText.setText(data.get(which)
                                                                            .get(FEED_SEARCH_TITLE));
                                                                    mUrlEditText.setText(data.get(which)
                                                                            .get(FEED_SEARCH_URL));
                                                                }
                                                            });
                                                    builder.show();
                                                }
                                            }

                                            @Override
                                            public void onLoaderReset(
                                                    Loader<ArrayList<HashMap<String, String>>> loader) {
                                            }
                                        });
                                break;

                            case R.id.byTopic:
                                mUrlEditText.setText("http://www.faroo.com/api?q=" + text
                                        + "&start=1&length=10&l=en&src=news&f=rss");
                                break;

                            case R.id.byYoutube:
                                mUrlEditText.setText("http://www.youtube.com/rss/user/"
                                        + text.replaceAll("\\+", "") + "/videos.rss");
                                break;
                            }
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, null).show();
        return true;
    }
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:cn.count.easydrive366.DriverLicenseEditActivity.java

private void chooseDriverType() {
    final JSONArray list = AppSettings.driver_type_list;
    if (list == null) {
        return;/*from  ww w  . j  a  va2  s  .  c  om*/
    }
    String types = ((TextView) findViewById(R.id.edt_driverlicense_car_type)).getText().toString();

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    MultiChoiceID.clear();
    builder.setIcon(R.drawable.ic_launcher);
    builder.setTitle(this.getResources().getString(R.string.app_name));

    final String[] items = new String[list.length()];
    boolean[] checkedItems = new boolean[list.length()];
    try {
        for (int i = 0; i < list.length(); i++) {
            JSONObject item = list.getJSONObject(i);
            String code = item.getString("code");
            String name = item.getString("name");
            String years = item.getString("years");
            items[i] = String.format("%s--%s(%s)", code, name, years);
            if (types.contains(code)) {
                checkedItems[i] = true;
                MultiChoiceID.add(i);
            } else {
                checkedItems[i] = false;
            }
        }
    } catch (Exception e) {
        log(e);
    }

    builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            if (isChecked) {
                if (!MultiChoiceID.contains(which))
                    MultiChoiceID.add(which);
            } else {
                if (MultiChoiceID.contains(which)) {
                    int i_index = MultiChoiceID.indexOf(which);
                    MultiChoiceID.remove(i_index);
                }
            }

        }
    });
    builder.setPositiveButton(this.getResources().getString(R.string.ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //            String str = "";
                    //                int size = MultiChoiceID.size();
                    //                for (int i = 0 ;i < size; i++) {
                    //                   str+= items[MultiChoiceID.get(i)] + ", ";
                    //                }
                    //                showDialog(str);
                    changeDriverType();
                }
            });
    builder.setNegativeButton(this.getResources().getString(R.string.cancel),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                }
            });
    builder.show();
}