Java Code Examples for android.app.AlertDialog

The following examples show how to use android.app.AlertDialog. These examples are extracted from open source projects.
Example 1
Project: iSCAU-Android   File: SpinnerDialog.java    License: GNU General Public License v3.0 6 votes vote down vote up
public AlertDialog.Builder createBuilder() {
    final Spinner mSpinner = new Spinner(mContext);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_dropdown_item, mList);
    mSpinner.setAdapter(adapter);
    mSpinner.setSelection(defaultPosition);
    setTitle(mText);
    setView(mSpinner);
    setNegativeButton(mContext.getString(R.string.btn_cancel), null);
    setPositiveButton(mContext.getString(R.string.btn_retry),
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                int n = mSpinner.getSelectedItemPosition();
                dialogListener.select(n);
            }

        });
    return this;
}
 
Example 2
Project: ContentProviderHelper   File: DeleteProviderDialog.java    License: MIT License 6 votes vote down vote up
@Override
public void onStart() {
	// super.onStart() is where dialog.show() is actually called on the underlying dialog,
	// so we have to do the validation and handling of the positive button after this point
	super.onStart();

	Button positiveButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
	positiveButton.setEnabled(false);
	positiveButton.setOnClickListener(new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			List<String> toDelete = new ArrayList<String>();
			for (int i = 0; i < mProviderCount; i++) {
				if (mCheckStates[i]) {
					toDelete.add(mProviderUris.get(i));
				}
			}
			getContract().onDeleteProviderClicked(toDelete);
			dismiss();
		}
	});
}
 
Example 3
Project: Favorite-Android-Client   File: welcome.java    License: Apache License 2.0 6 votes vote down vote up
public void SignupWithoutIDAlert() {
	// Alert
	AlertDialog.Builder builder = new AlertDialog.Builder(welcome.this);
	builder.setMessage(getString(R.string.sign_up_without_id_des)).setTitle(
			getString(R.string.alert));
	builder.setPositiveButton(getString(R.string.continu),
			new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					
					Intent intent = new Intent(welcome.this, join.class); 
					startActivity(intent);
					finish();

				}
			});
	builder.setNegativeButton(getString(R.string.no), null);
	builder.show();

}
 
Example 4
Project: Bluefruit_LE_Connect_Android_V2   File: MainActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == kActivityRequestCode_EnableBluetooth) {
        if (resultCode == Activity.RESULT_OK) {
            checkPermissions();
        } else if (resultCode == Activity.RESULT_CANCELED) {
            if (!isFinishing()) {
                hasUserAlreadyBeenAskedAboutBluetoothStatus = true;     // Remember that
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                AlertDialog dialog = builder.setMessage(R.string.bluetooth_poweredoff)
                        .setPositiveButton(android.R.string.ok, null)
                        .show();
                DialogUtils.keepDialogOnOrientationChanges(dialog);
            }
        }
    }
}
 
Example 5
Project: Android-Keyboard   File: LatinIME.java    License: Apache License 2.0 6 votes vote down vote up
private void showOptionDialog(final AlertDialog dialog) {
    final IBinder windowToken = KeyboardSwitcher.getInstance().getMainKeyboardView().getWindowToken();
    if (windowToken == null) {
        return;
    }

    final Window window = dialog.getWindow();
    final WindowManager.LayoutParams lp = window.getAttributes();
    lp.token = windowToken;
    lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
    window.setAttributes(lp);
    window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

    mOptionsDialog = dialog;
    dialog.show();
}
 
Example 6
Project: v9porn   File: HostJsScope.java    License: MIT License 6 votes vote down vote up
/**
 * 系统弹出提示框
 *
 * @param webView 浏览器
 * @param message 提示信息
 */
public static void alert(WebView webView, String message) {
    // 构建一个Builder来显示网页中的alert对话框
    AlertDialog.Builder builder = new AlertDialog.Builder(webView.getContext());
    builder.setTitle(webView.getContext().getString(R.string.dialog_title_system_msg));
    builder.setMessage(message);
    builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    builder.setCancelable(false);
    builder.create();
    builder.show();
}
 
Example 7
Project: materialistic   File: DrawerActivityLoginTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddAccount() {
    AccountManager.get(activity).addAccountExplicitly(new Account("existing",
            BuildConfig.APPLICATION_ID), "password", null);
    drawerAccount.performClick();
    AlertDialog alertDialog = ShadowAlertDialog.getLatestAlertDialog();
    assertNotNull(alertDialog);
    assertThat(alertDialog.getListView().getAdapter()).hasCount(1);
    alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick();
    assertThat(alertDialog).isNotShowing();
    ((ShadowSupportDrawerLayout) Shadow.extract(activity.findViewById(R.id.drawer_layout)))
            .getDrawerListeners().get(0)
            .onDrawerClosed(activity.findViewById(R.id.drawer));
    assertThat(shadowOf(activity).getNextStartedActivity())
            .hasComponent(activity, LoginActivity.class);
}
 
Example 8
Project: MOAAP   File: CameraBridgeViewBase.java    License: MIT License 6 votes vote down vote up
private void onEnterStartedState() {
    Log.d(TAG, "call onEnterStartedState");
    /* Connect camera */
    if (!connectCamera(getWidth(), getHeight())) {
        AlertDialog ad = new AlertDialog.Builder(getContext()).create();
        ad.setCancelable(false); // This blocks the 'BACK' button
        ad.setMessage("It seems that you device does not support camera (or it is locked). Application will be closed.");
        ad.setButton(DialogInterface.BUTTON_NEUTRAL,  "OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ((Activity) getContext()).finish();
            }
        });
        ad.show();

    }
}
 
Example 9
Project: DeviceConnect-Android   File: ProgressDialogFragment.java    License: MIT License 6 votes vote down vote up
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
    Bundle args = getArguments();

    String msg = "";
    if (args != null) {
        msg = args.getString(EXTRA_MSG);
    }

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View v = inflater.inflate(R.layout.dialog_setting_progress, null);
    TextView messageView = v.findViewById(R.id.message);
    messageView.setText(msg);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);
    builder.setCancelable(false);

    AlertDialog dialog = builder.create();
    dialog.setCanceledOnTouchOutside(false);
    return dialog;
}
 
Example 10
Project: tapchat-android   File: BufferFragment.java    License: Apache License 2.0 6 votes vote down vote up
private void sendMessage() {
    EditText textEntry = (EditText) getView().findViewById(R.id.text_entry);
    final String text = textEntry.getText().toString();

    if (TextUtils.isEmpty(text)) {
        return;
    }

    if (text.startsWith("/")) {
        new AlertDialog.Builder(getActivity())
                .setMessage(R.string.commands_not_supported)
                .setPositiveButton(android.R.string.ok, null)
                .show();
        return;
    }

    textEntry.setText("");

    mConnection.say(mBuffer.getName(), text, null);
}
 
Example 11
Project: SimpleProject   File: BaseDialog.java    License: MIT License 6 votes vote down vote up
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
	AlertDialog.Builder builder;
	if (dialogStyle == DIALOG_STYLE_MATERIAL) {
		builder = new AlertDialog.Builder(getContext());
		if (!TextUtils.isEmpty(title)) {
			builder.setTitle(title);
		}
		if (cancelListener != null) {
			builder.setNegativeButton(cancelText, cancelListener);
		}
		if (okListener != null) {
			builder.setPositiveButton(okText, okListener);
		}
		initMaterialDialog(builder);
	} else {
		builder = new AlertDialog.Builder(getContext(), R.style.CommonDialog);
		initCustomDialog(builder);
	}

	return builder.create();
}
 
Example 12
Project: RedReader   File: SessionListDialog.java    License: GNU General Public License v3.0 6 votes vote down vote up
@NonNull
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
	super.onCreateDialog(savedInstanceState);

	if (alreadyCreated) return getDialog();
	alreadyCreated = true;

	final Context context = getContext();

	final AlertDialog.Builder builder = new AlertDialog.Builder(context);
	builder.setTitle(context.getString(R.string.options_past));

	rv = new RecyclerView(context);
	builder.setView(rv);

	rv.setLayoutManager(new LinearLayoutManager(context));
	rv.setAdapter(new SessionListAdapter(context, url, current, type, this));
	rv.setHasFixedSize(true);

	RedditAccountManager.getInstance(context).addUpdateListener(this);

	builder.setNeutralButton(context.getString(R.string.dialog_close), null);

	return builder.create();
}
 
Example 13
Project: BotLibre   File: IntentIntegrator.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Shares the given text by encoding it as a barcode, such that another user can
 * scan the text off the screen of the device.
 *
 * @param text the text string to encode as a barcode
 * @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type} constants.
 * @return the {@link AlertDialog} that was shown to the user prompting them to download the app
 *   if a prompt was needed, or null otherwise
 */
public final AlertDialog shareText(CharSequence text, CharSequence type) {
  Intent intent = new Intent();
  intent.addCategory(Intent.CATEGORY_DEFAULT);
  intent.setAction(BS_PACKAGE + ".ENCODE");
  intent.putExtra("ENCODE_TYPE", type);
  intent.putExtra("ENCODE_DATA", text);
  String targetAppPackage = findTargetAppPackage(intent);
  if (targetAppPackage == null) {
    return showDownloadDialog();
  }
  intent.setPackage(targetAppPackage);
  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
  attachMoreExtras(intent);
  if (fragment == null) {
    activity.startActivity(intent);
  } else {
    fragment.startActivity(intent);
  }
  return null;
}
 
Example 14
Project: FacebookNewsfeedSample-Android   File: LogicActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void onNavigateButtonClick(Button source) {
    activeTab = source.getText().toString();

    logicGroup.setVisibility(getGroupVisibility(source, logicButton));
    friendsGroup.setVisibility(getGroupVisibility(source, friendsButton));
    settingsGroup.setVisibility(getGroupVisibility(source, settingsButton));
    contentGroup.setVisibility(getGroupVisibility(source, contentButton));

    // Show an error if viewing friends and there is no logged in user.
    if (source == friendsButton) {
        Session session = Session.getActiveSession();
        if ((session == null) || !session.isOpened()) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.feature_requires_login_title)
                    .setMessage(R.string.feature_requires_login_message)
                    .setPositiveButton(R.string.ok_button, null)
                    .show();
        }
    }
}
 
Example 15
Project: zom-android-matrix   File: OnboardingActivity.java    License: Apache License 2.0 6 votes vote down vote up
public void showUpgradeMessage () {

        if (TextUtils.isEmpty(Preferences.getValue("showUpgradeMessage"))) {

            android.support.v7.app.AlertDialog alertDialog = new android.support.v7.app.AlertDialog.Builder(this).create();
            alertDialog.setTitle(R.string.welcome_message);
            alertDialog.setMessage(this.getString(R.string.upgrade_message));
            alertDialog.setButton(android.support.v7.app.AlertDialog.BUTTON_NEUTRAL, this.getString(R.string.ok),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            alertDialog.show();

            PreferenceManager.getDefaultSharedPreferences(this).edit().putString("showUpgradeMessage","false").commit();

        }


    }
 
Example 16
Project: appcan-android   File: EBrowserActivity.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
private final void loadResError() {
    AlertDialog.Builder dia = new AlertDialog.Builder(this);
    ResoureFinder finder = ResoureFinder.getInstance();
    dia.setTitle(finder.getString(this, "browser_dialog_error"));
    dia.setMessage(finder.getString(this, "browser_init_error"));
    dia.setCancelable(false);
    dia.setPositiveButton(finder.getString(this, "confirm"),
            new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                    Process.killProcess(Process.myPid());
                }
            });
    dia.create();
    dia.show();
}
 
Example 17
Project: AndroidFaceRecognizer   File: FaceRecognitionActivity.java    License: MIT License 6 votes vote down vote up
private void showAlert(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
 
	alertDialogBuilder.setTitle("Face Detection Training");
 
	alertDialogBuilder
		.setMessage("Ten samples should be for saving!")
		.setCancelable(false)
		.setPositiveButton("OK",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				dialog.cancel();
			}
		  });
 
		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();
 
		// show it
		alertDialog.show();
  }
 
Example 18
Project: LibreTrivia   File: TriviaGameActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onBackPressed() {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame_trivia_game);

    if (fragment instanceof TriviaGameErrorFragment) {
        super.onBackPressed();
    } else {
        new AlertDialog.Builder(this)
                .setTitle(R.string.ui_quit_game)
                .setMessage(R.string.ui_quit_game_msg)
                .setPositiveButton(android.R.string.yes, (dialog, which) ->
                        TriviaGameActivity.super.onBackPressed())
                .setNegativeButton(android.R.string.no, (dialog, which) -> {
                })
                .show();
    }
}
 
Example 19
Project: SimpleUsbTerminal   File: TerminalFragment.java    License: MIT License 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.clear) {
        receiveText.setText("");
        return true;
    } else if (id ==R.id.newline) {
        String[] newlineNames = getResources().getStringArray(R.array.newline_names);
        String[] newlineValues = getResources().getStringArray(R.array.newline_values);
        int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Newline");
        builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
            newline = newlineValues[item1];
            dialog.dismiss();
        });
        builder.create().show();
        return true;
    } else {
        return super.onOptionsItemSelected(item);
    }
}
 
Example 20
Project: pushy-demo-android   File: Main.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onPostExecute(Exception exc) {
    // Activity died?
    if (isFinishing()) {
        return;
    }

    // Hide progress bar
    mLoading.dismiss();

    // Registration failed?
    if (exc != null) {
        // Write error to logcat
        Log.e("Pushy", "Registration failed: " + exc.getMessage());

        // Display error dialog
        new AlertDialog.Builder(Main.this).setTitle(R.string.registrationError)
                .setMessage(exc.getMessage())
                .setPositiveButton(R.string.ok, null)
                .create()
                .show();
    }

    // Update UI with registration result
    updateUI();
}
 
Example 21
Project: BatteryFu   File: Utils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prompt user whether to proceed or not, if so, execute runnable
 * 
 * @param context
 * @param titleResId
 * @param msgResId
 * @param onConfirm
 */
public static void confirm(Context context, String logTag, int titleResId, int msgResId,
         int OkResId, int cancelResId, final Runnable onConfirm) {
   AlertDialog dialog = null;
   try {
      Builder b = new Builder(context);
      b.setCancelable(true);
      if (titleResId >= 0) b.setTitle(titleResId);
      if (msgResId >= 0) b.setMessage(msgResId);
      if (cancelResId >= 0) b.setNegativeButton(cancelResId, null);
      if (onConfirm != null && OkResId >= 0) b.setPositiveButton(OkResId, new OnClickListener() {
         @Override
         public void onClick(DialogInterface arg0, int arg1) {
            onConfirm.run();
         }
      });

      b.create().show();
   } catch (Exception e) {
      if (logTag != null) Utils.handleException(logTag, context, e);
   }
}
 
Example 22
Project: MCPDict   File: FavoriteDialogs.java    License: MIT License 6 votes vote down vote up
public static void add(final char unicode) {
    final EditText editText = new EditText(activity);
    editText.setHint(R.string.favorite_add_hint);
    editText.setSingleLine(false);
    new AlertDialog.Builder(activity)
        .setIcon(R.drawable.ic_star_yellow)
        .setTitle(String.format(activity.getString(R.string.favorite_add), unicode))
        .setView(editText)
        .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String comment = editText.getText().toString();
                UserDatabase.insertFavorite(unicode, comment);
                String message = String.format(activity.getString(R.string.favorite_add_done), unicode);
                Boast.showText(activity, message, Toast.LENGTH_SHORT);
                FavoriteFragment fragment = activity.getFavoriteFragment();
                if (fragment != null) {
                    fragment.notifyAddItem();
                }
                activity.getCurrentFragment().refresh();
            }
        })
        .setNegativeButton(R.string.cancel, null)
        .show();
}
 
Example 23
Project: myapplication   File: MeAvatarShowerAty.java    License: Apache License 2.0 6 votes vote down vote up
private void eventDeal() {
    AppUser appUser = BmobUser.getCurrentUser(AppUser.class);
    String avatarUrl = appUser.getUserAvatarUrl();

    Glide.with(MeAvatarShowerAty.this)
            .load(avatarUrl)
            .error(R.drawable.app_icon)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .into(avatarImv);

    photoViewAttacher = new PhotoViewAttacher(avatarImv);
    photoViewAttacher.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            String[] choices = {"保存至本地"};
            //包含多个选项的对话框
            AlertDialog dialog = new AlertDialog.Builder(MeAvatarShowerAty.this)
                    .setItems(choices, onselect).create();
            dialog.show();
            return true;
        }
    });
}
 
Example 24
Project: UMS-Interface   File: FrameActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void initShell()
{
    ShellUnit.initBusybox(getResources().openRawResource(R.raw.busybox));
    if(!ShellUnit.sRootReady)
        new AlertDialog.Builder(this).setTitle(R.string.error).setMessage(R.string.no_root_tip)
        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                FrameActivity.this.finish();
            }
        }).create().show();
    if(!ShellUnit.sSuReady||!ShellUnit.sBusyboxReady)
        Toast.makeText(this,getString(R.string.init_fail),Toast.LENGTH_LONG).show();
    logInfo("SUReady="+ShellUnit.sSuReady+";BusyboxReady="+ShellUnit.sBusyboxReady);
    ShellUnit.execBusybox("echo 'initShell finished'");
}
 
Example 25
Project: pasm-yolov3-Android   File: CameraBridgeViewBase.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void onEnterStartedState() {
    Log.d(TAG, "call onEnterStartedState");
    /* Connect camera */
    if (!connectCamera(getWidth(), getHeight())) {
        AlertDialog ad = new AlertDialog.Builder(getContext()).create();
        ad.setCancelable(false); // This blocks the 'BACK' button
        ad.setMessage("It seems that you device does not support camera (or it is locked). Application will be closed.");
        ad.setButton(DialogInterface.BUTTON_NEUTRAL,  "OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ((Activity) getContext()).finish();
            }
        });
        ad.show();

    }
}
 
Example 26
Project: xDrip   File: LocationHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Prompt the user to enable location if it isn't already on.
 *
 * @param parent The currently visible activity.
 */
public static void requestLocation(final Activity parent) {
    if (LocationHelper.isLocationEnabled(parent)) {
        return;
    }

    // Shamelessly borrowed from http://stackoverflow.com/a/10311877/868533

    AlertDialog.Builder builder = new AlertDialog.Builder(parent);
    builder.setTitle(R.string.location_not_found_title);
    builder.setMessage(R.string.location_not_found_message);
    builder.setPositiveButton(R.string.location_yes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
            parent.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    });
    builder.setNegativeButton(R.string.no, null);
    try {
        builder.create().show();
    } catch (RuntimeException e) {
        Looper.prepare();
        builder.create().show();
    }
}
 
Example 27
Project: Botifier   File: BlackListFragment.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
	AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
	final EditText input = new EditText(getActivity());
    builder.setView(input);
    builder.setTitle(R.string.blacklist_add);
    builder.setMessage(R.string.blacklist_desc);
    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        //@Override
        public void onClick(DialogInterface dialog, int which) {
            Editable value = input.getText();
            addEntry(value.toString());

        }
    });
    builder.show();
    
	return super.onOptionsItemSelected(item);
}
 
Example 28
Project: q-municate-android   File: SystemPermissionHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Bundle arguments = getArguments();
    final int requestCode = arguments.getInt(ARGUMENT_PERMISSION_REQUEST_CODE);
    finishActivity = arguments.getBoolean(ARGUMENT_FINISH_ACTIVITY);

    return new AlertDialog.Builder(getActivity())
            .setMessage(R.string.permission_rationale_location)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // After click on Ok, request the permission.
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            requestCode);
                    // Do not finish the Activity while requesting permission.
                    finishActivity = false;
                }
            })
            .setNegativeButton(android.R.string.cancel, null)
            .create();
}
 
Example 29
Project: mobile-manager-tool   File: SizeLimitActivity.java    License: MIT License 6 votes vote down vote up
private void showDialog(Cursor cursor) {
        int size = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.COLUMN_TOTAL_BYTES));
        String sizeString = Formatter.formatFileSize(this, size);
        String queueText = "Queue";
        boolean isWifiRequired =
            mCurrentIntent.getExtras().getBoolean(DownloadInfo.EXTRA_IS_WIFI_REQUIRED);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        if (isWifiRequired) {
//            builder.setTitle(R.string.wifi_required_title)
//                    .setMessage(getString(R.string.wifi_required_body, sizeString, queueText))
//                    .setPositiveButton(R.string.button_queue_for_wifi, this)
//                    .setNegativeButton(R.string.button_cancel_download, this);
//        } else {
//            builder.setTitle(R.string.wifi_recommended_title)
//                    .setMessage(getString(R.string.wifi_recommended_body, sizeString, queueText))
//                    .setPositiveButton(R.string.button_start_now, this)
//                    .setNegativeButton(R.string.button_queue_for_wifi, this);
//        }
        mDialog = builder.setOnCancelListener(this).show();
    }
 
Example 30
Project: react-native-android-vitamio   File: VideoView.java    License: MIT License 6 votes vote down vote up
public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
  Log.d("Error: %d, %d", framework_err, impl_err);
  mCurrentState = STATE_ERROR;
  mTargetState = STATE_ERROR;
  if (mMediaController != null)
    mMediaController.hide();

  if (mOnErrorListener != null) {
    if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err))
      return true;
  }

  if (getWindowToken() != null) {
    int message = framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK ? getResources().getIdentifier("VideoView_error_text_invalid_progressive_playback", "string", mContext.getPackageName()): getResources().getIdentifier("VideoView_error_text_unknown", "string", mContext.getPackageName());

    new AlertDialog.Builder(mContext).setTitle(getResources().getIdentifier("VideoView_error_title", "string", mContext.getPackageName())).setMessage(message).setPositiveButton(getResources().getIdentifier("VideoView_error_button", "string", mContext.getPackageName()), new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        if (mOnCompletionListener != null)
          mOnCompletionListener.onCompletion(mMediaPlayer);
      }
    }).setCancelable(false).show();
  }
  return true;
}
 
Example 31
Project: LaunchEnr   File: Launcher.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void onClickPendingAppItem(final View v, final String packageName,
        boolean downloadStarted) {
    if (downloadStarted) {
        // If the download has started, simply direct to the market app.
        startMarketIntentForPackage(v, packageName);
        return;
    }
    new AlertDialog.Builder(this)
        .setTitle(R.string.abandoned_promises_title)
        .setMessage(R.string.abandoned_promise_explanation)
        .setPositiveButton(R.string.abandoned_search, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                startMarketIntentForPackage(v, packageName);
            }
        })
        .setNeutralButton(R.string.abandoned_clean_this,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    final UserHandle user = Process.myUserHandle();
                    mWorkspace.removeAbandonedPromise(packageName, user);
                }
            })
        .create().show();
}
 
Example 32
Project: Paddle-Lite-Demo   File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("Permission denied")
                .setMessage("Click to force quit the app, then open Settings->Apps & notifications->Target " +
                        "App->Permissions to grant all of the permissions.")
                .setCancelable(false)
                .setPositiveButton("Exit", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.this.finish();
                    }
                }).show();
    }
}
 
Example 33
Project: tapchat-android   File: TapchatServiceStatusBar.java    License: Apache License 2.0 6 votes vote down vote up
@Subscribe public void onServiceError(ServiceErrorEvent event) {
    final Exception error = event.getError();

    if (error instanceof HttpResponseException) {
        HttpResponseException httpError = (HttpResponseException) error;
        if (httpError.getStatusCode() == 403) {
            mService.logout();
            Toast.makeText(mActivity, R.string.unauthorized, Toast.LENGTH_LONG).show();
            mActivity.startActivity(new Intent(mActivity, WelcomeActivity.class));
            mActivity.finish();
            return;
        }
    }

    new AlertDialog.Builder(mActivity)
        .setTitle(R.string.error)
        .setMessage(error.toString())
        .setPositiveButton(android.R.string.ok, null)
        .show();
}
 
Example 34
Project: AndroidApp   File: BarcodeCaptureActivity.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Callback for the result from requesting permissions. This method
 * is invoked for every call on {@link #requestPermissions(String[], int)}.
 * <p>
 * <strong>Note:</strong> It is possible that the permissions request interaction
 * with the user is interrupted. In this case you will receive empty permissions
 * and results arrays which should be treated as a cancellation.
 * </p>
 *
 * @param requestCode  The request code passed in {@link #requestPermissions(String[], int)}.
 * @param permissions  The requested permissions. Never null.
 * @param grantResults The grant results for the corresponding permissions
 *                     which is either {@link PackageManager#PERMISSION_GRANTED}
 *                     or {@link PackageManager#PERMISSION_DENIED}. Never null.
 * @see #requestPermissions(String[], int)
 */
@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode != RC_HANDLE_CAMERA_PERM) {
        Log.d(TAG, "Got unexpected permission result: " + requestCode);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        return;
    }

    if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "Camera permission granted - initialize the camera source");
        // we have permission, so create the camerasource
        createCameraSource();
        return;
    }

    Log.e(TAG, "Permission not granted: results len = " + grantResults.length +
            " Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)"));

    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            finish();
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("emoncms Barcode Scanner")
            .setMessage(R.string.no_camera_permission)
            .setPositiveButton(R.string.ok, listener)
            .show();
}
 
Example 35
Project: USB_Mass_Storage_Enabler   File: RootHelper.java    License: MIT License 5 votes vote down vote up
void executeAsSU(final String command) {

        Command cmd = new Command(0, command);

        try {
            if(rootShell==null || rootShell.isClosed) getRootShell();
            rootShell.add(cmd);
        } catch (final Exception e) {
            e.printStackTrace();
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    AlertDialog.Builder fail = new AlertDialog.Builder(activity);
                    fail.setTitle(context.getString(R.string.error_general));
                    CharSequence msg = context.getString(R.string.error_execution)+"\n\n"+command+"\n\n"+e.getMessage()+"\n\n"+context.getString(R.string.error_contact);
                    fail.setMessage(msg);
                    fail.setPositiveButton(context.getString(R.string.action_ok),new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            activity.finish();
                        }
                    });

                    fail.setCancelable(false);
                    fail.create();
                    fail.show();
                }
            });
        }

    }
 
Example 36
Project: BotLibre   File: MainActivity.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static void confirm(String message, Activity activity, Boolean cancelable, DialogInterface.OnClickListener listener) {
	AlertDialog dialog = new AlertDialog.Builder(activity).create();
	dialog.setTitle(activity.getString(R.string.title));
	dialog.setMessage(message);
	dialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", listener);
	dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "NO", listener);
	if(cancelable){dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Cancel",listener);}
	dialog.show();
}
 
Example 37
Project: drmips   File: DlgConfirmReplace.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
	super.onCreateDialog(savedInstanceState);

	Bundle args = getArguments();
	String path = args.getString("path");
	String name = path != null ? new File(path).getName() : "?";

	return new AlertDialog.Builder(getActivity())
		.setMessage(getString(R.string.confirm_replace).replace("#1", name))
		.setPositiveButton(android.R.string.ok, this)
		.setNegativeButton(android.R.string.cancel, this)
		.create();
}
 
Example 38
Project: barterli_android   File: AbstractBarterLiFragment.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Show the dialog for the user to add his name, in case it's not already added
 */
protected void showAddFirstNameDialog() {

    mAddUserInfoDialogFragment = new AddUserInfoDialogFragment();
    mAddUserInfoDialogFragment
            .show(AlertDialog.THEME_HOLO_LIGHT, 0, R.string.update_info, R.string.submit,
                  R.string.cancel, 0, getFragmentManager(), true, FragmentTags.DIALOG_ADD_NAME);
}
 
Example 39
Project: prevent   File: UserGuideActivity.java    License: Do What The F*ck You Want To Public License 5 votes vote down vote up
private void showVersionInfo() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(getString(R.string.app_name) + "(" + BuildConfig.VERSION_NAME + ")");
    builder.setMessage(getVersionInfo(false));
    builder.setIcon(R.drawable.ic_launcher);
    builder.setPositiveButton(getString(android.R.string.copy), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            DeprecatedUtils.setClipboard(getBaseContext(), getVersionInfo(true));
        }
    });
    builder.create().show();
}
 
Example 40
Project: ContentProviderHelper   File: MainActivity.java    License: MIT License 5 votes vote down vote up
private void toggleColumnTypes() {
	if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
		String message = String.format(getString(R.string.api_level), Build.VERSION.SDK_INT);
		new AlertDialog.Builder(mContext)//
				.setTitle(R.string.info)//
				.setMessage(message)//
				.setNeutralButton(R.string.ok, null)//
				.show();
	} else {
		mShowColumnTypes = !mShowColumnTypes;
		mAdapterColumns.showTypes(mShowColumnTypes);
		mButtonTypes.setText(mShowColumnTypes ? R.string.hide_column_types : R.string.show_column_types);
	}
}