I have an AlertDialog in android studio as shown below:
final EditText columninput = new EditText(this);
columninput.setInputType(InputType.TYPE_CLASS_NUMBER);
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose column number");
adb.setView(columninput);
adb.setMessage("Please specify the number of columns you would like to decrypt your message with.");
adb.setCancelable(true);
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
boolean bool = true;
try {
col = Integer.parseInt(columninput.getText().toString());
}
catch (Exception e) {
bool = false;
Toast t = Toast.makeText(getApplicationContext(), "Incorrect input", Toast.LENGTH_LONG);
t.show();
}
if (bool) {
dialog.dismiss();
}
}
});
adb.show();
method1(toRead, col);
Note that toRead is another variable dealt with outside of this context; it should not be causing any errors. When I run my application, the AlertDialog is never shown, and method1 runs immediately. However, when I comment out the last line (method1(toRead, col)), the alertdialog appears when the application is run. Why is this, and how can I ensure that the alertDialog is always shown?
This issue appears because, when you open AlertDialog, the activity goes into pause state.
So, when you hide the last line and don't call the method the activity is able to go into Pause state and the AlertDialog appears successfully.
While in the other case, when the last method is called, what happens is:
before your AlertDialog gets created, the method1() gets called.
I hope this helps.
May this helps you:
Example:
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Delete")
.setMessage("Are you sure you want to delete Product?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbni.delete(ItemID);
arrayStudent = dbni.selectAll();
list_view.setAdapter(new Adapter_viewitem(mactivity, arrayStudent));
Toast.makeText(getApplicationContext(), "Product deleted successfully", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("No", null).show();
Related
In my application I have a button that when pressed I want it to display an Alert Dialog Box that asks if you want to continue. It will have two buttons: a "Continue" and "Do Not Continue". I am putting the method that opens up the dialog box within the method that opens the new Activity like so:
case R.id.bRegister:
try{
//the method for opening the alert box goes somewhere here but i don't know where yet.
Class ourClass = Class.forName("org.health.blablablabla.app.RegisterData");
Intent ourIntent = new Intent(MainActivity.this,ourClass);
finish();
startActivity(ourIntent);
overridePendingTransition(R.animator.fadein,R.animator.fadeout);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
This is currently what I have for the Alert Dialog Box method:
private void showWarning(){
AlertDialog.Builder warning = new AlertDialog.Builder(this);
warning.setTitle("Existing Data");
warning.setMessage("There is already existing data. If you continue all previous data will be deleted. Are you sure you want to continue?");
warning.setPositiveButton("Continue",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1)
{
arg0.dismiss();
}
});
warning.setNegativeButton("Do Not Continue",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
}
My question is where to put the method in the first block of code, and how do I make it so that when the "Do Not Continue" button is pressed, the New Activity "RegisterData" doesn't open up.
you can make an YesNoSampleActivity and use AlertDialog.Builder like this:
public class YesNoSampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Put up the Yes/No message box
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle("Erase hard drive")
.setMessage("Are you sure?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Yes button clicked, do something
Toast.makeText(YesNoSampleActivity.this, "Yes button pressed",
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", null) //Do nothing on no
.show();
// Continue code after the Yes/No dialog
// ....
}
}
So in my android application, I have a helper class which can create a dialog box using the following code:
public void CreateAlert(String title, String message)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) { }
});
// Showing Alert Message
alertDialog.show();
}
In my registrar activity, I have an ASyncTask that runs a particular task, following which it processes a boolean variable with the below function:
private void Process(boolean Success)
{
if(Success)
{
appHelper.CreateAlert("Success!", "Well Done!");
// Progress to the activity
startActivity( new Intent(context, Menu.class) );
getActivity().finish();
}
else
{
appHelper.CreateAlert("Failure!", "Please try again.");
}
}
However as you can see from the above code, I am wanting to start an activity based on a succesful result. However, I need the application to wait for the user to click the okay button on the dialog before progressing to the next activity.
What is the best way for this to be done?
EDIT: I should note that the two functions are in different classes, CreateAlert is in a class called AppHelper where as Process is inside Registrar.class, an activity.
Check again the status of boolean success in the click listener of alertDialog's OK button
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
if(Success)
{
// Progress to the activity
context.startActivity( new Intent(context, Menu.class) );
context.getActivity().finish();
}
else
{
// Don't do anything
}
});
and update your Process like below
private void Process(boolean Success)
{
if(Success)
{
appHelper.CreateAlert("Success!", "Well Done!");
}
else
{
appHelper.CreateAlert("Failure!", "Please try again.");
}
}
The code is not working. Please help me. It print the replace all string, but further code is not running.
when I debug this, there is no error in the code. It will show the code of alert box.
if(count>0)
{
System.out.println("replace all string name ");
// final Intent intent_ul=new Intent(this, UploadExcel.class);
AlertDialog.Builder alertDialogBuilder_ue = new AlertDialog.Builder(this);
alertDialogBuilder_ue.setTitle("Alert!!");
alertDialogBuilder_ue
.setMessage("Are you sure you want to Replace all the data related to this style ? ")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.delete_style_measurement(style_no);
Log.d("","yes click");
count=0;
mySQLiteAdapter.close();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Log.d("","No click");
count++;
dialog.cancel();
// startActivity(intent_ul);
//finish();
}
});
}
Add these lines before the end of if condition
AlertDialog alertDialog = alertDialogBuilder_ue.create();
alertDialog.show();
You need to add
alertDialogBuilder_ue.show();
in your code
Check with this code. This code working for me
Context context = CurrentActivity.this;
AlertDialog.Builder ad = new AlertDialog.Builder(context);
ad.setTitle("Application");
ad.setMessage("Do you want to proceed?");
ad.setPositiveButton("Yes", new OnClickListener()
{
public void onClick(DialogInterface dialog, int arg1)
{
}
});
ad.setNegativeButton("Cancel", new OnClickListener()
{
public void onClick(DialogInterface dialog, int arg1)
{
}
});
ad.setCancelable(false);
ad.show();
In your code adding alertDialogBuilder_ue.show(); should make the dialog appear.
By some people it has been suggested that you have to use alertDialogBuilder_ue.create(); to get a handle to the AlertDialog that you can then use the .show() method on.
Both are possibilities but you don't have to use the .create() option if you don't need a handle to the AlertDialog
I'm currently developing an app that will allow the user to choose an app and launch it at a later time (there is more functionality but this is the main thing I'm having an issue with.)
I'm looking for a way to get a list of the applications (user installed or updateable ex. Gmail, GMaps, etc...) And throw it into an AlertDialog similar to how you add a shortcut to the Homescreen (Long press -> Applications).
This is the thread I'm using that has the code to get the list of applications that I need. However how would I turn this into an AlertDialog?
Here is the code from the thread.
public void getApps()
{
PackageManager pm = getPackageManager();
List<ApplicationInfo> apps = pm.getInstalledApplications(0);
List<ApplicationInfo> installedApps = new ArrayList<ApplicationInfo>();
for(ApplicationInfo app : apps) {
//checks for flags; if flagged, check if updated system app
if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1) {
installedApps.add(app);
//it's a system app, not interested
} else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
//Discard this one
//in this case, it should be a user-installed app
} else {
installedApps.add(app);
}
}
}//end getApps()
And here is the code I use for displaying an AlertDialog similar to what I want to use.
//PseudoCode does not compile
public void displayAppList(View v)
{
final CharSequence[] items = {getApps()};
AlertDialog.Builder builder = new AlertDialog.Builder(SchedulerActivity.this);
builder.setTitle("Choose an App To Launch");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
appChoiceString[count] = items[item];
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(SchedulerActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(SchedulerActivity.this, "Fail", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Any help as to getting this to display properly would be awesome.
Why not just use the standard intent chooser? (See this). Otherwise, you probably want to explain what is not displaying the way you want, and how you really want it to look in detail.
I am validating an AlertDialog, and I would like to raise a Toast on top of the AlertDialog display.
I have this code, but the Toast is displayed on the activity
new AlertDialog.Builder(this).setTitle(R.string.contact_groups_add)
.setView(addView).setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
if (wrapper.getTitle().length()>0)
{
processAdd(wrapper);
} else {
Toast.makeText(getApplicationContext(), "Name is required", Toast.LENGTH_SHORT).show();
}
}
}).setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// ignore, just dismiss
}
}).show();
Instead of using AdvertDialog.Builder, you can create a custom dialog which will behave like a dialog, but is in fact a normal activity. Your toasts should be drawn normally on top of this.
Had this problem myself as well, when I wanted to show a validation message within a dialog.
The answer that seanhodges gave is probably the cleaner and better way. But a seperate activity wasnt practical for me, so i came up with this solution.
Anyway, you can use the AlerDialog.Builder, and show a toast.
If you override the OnClickListener of the button the you want to trigger the toast, you can show a toast on top of a dialog.
An example;
public void showToastOnDialog(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Dialog title");
builder.setMessage("Dialog message");
builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing, you will be overriding this anyway
}
});
builder.setNegativeButton(android.R.string.cancel,
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// You can implement code here, because you wont be
// overriding this
}
});
final AlertDialog dialog = builder.create();
// Make sure you show the dialog first before overriding the
// OnClickListener
dialog.show();
// Notice that I`m not using DialogInterface.OnClicklistener but the
// View.OnClickListener
dialog.getButton(Dialog.BUTTON_POSITIVE).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast toast = Toast.makeText(context,
"I`m a toast on top of a dialog.",
Toast.LENGTH_LONG);
toast.show();
// Because you are overriding the OnClicklistener, the
// dialog will not auto dismiss
// after clicking
dialog.dismiss();
}
});
}
Try this:
AlertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);