In my android application, I use one alert dialog to display some information to the user, and if the user click the dialog , it should finish the activity. My code is
offer.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
AlertDialog alert=new AlertDialog.Builder(offer.this).create();
alert.setTitle("SVSugar Mill");
alert.setMessage("Offer Number is "+offer_no.getText().toString());
alert.setButton("Click to Dismiss", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
//return;
}
});
alert.show();
}
});
It doesn't wait for the user response to finish(). Instead it will be called even if the user didn't click the Alert dialog. I know this is asynchronous, but I need to do this.(The OfferNO should be displayed to the user. When the user click the alert dialog it should finish the activity). Is there any way to do this?
Someone help me
Edit:
The activity will be finished without waiting for the user to click the alert dialog
public void ShowDialog(final Context context) {
new AlertDialog.Builder(context)
.setTitle(android.R.string.dialog_alert_title)
.setMessage(UContext.getContext().getString(R.string.network_error))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
this.finish();
}
}).show();
}
The problem is that you created two AlertDialog instances here:
alertDialog=builder.create();
builder.create().show();
Then you called dismiss() on the dialog that is not actually shown. This should fix the problem:
alertDialog=builder.show();
Related
Please, i would like to show back details after the user must have input something, back on alert dialog box in Android studio. I used this code below:
editText = (EditText) findViewById(R.id.my_edit_txt);
editText.getText().toString();
But it doesn't show on the confirmation dialog box I created.
It looks like you didn't set the text of your AlertDialog, but this is just an assumption because there is not enough code in your question. Calling editText.getText().toString() does not do anything but return a String. It does not assign it to anything. An example with an AlertDialog would be the following:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(editText.getText().toString());
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Set other dialog properties
...
// Create the AlertDialog
AlertDialog dialog = builder.create();
I've took this example from Android Developers and modified it so that it includes the text of your EditText. This code should work because you not only call the toString() method but also assign it's return value to the AlertDialog's message property.
This is my entire code for the alert dialog box:
public void alertdialog(View view){
mybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder cfmalt = new AlertDialog.Builder(Dashboard.this);
//cfmalt.setMessage("Do you want to quit?").setCancelable(false);
//editText.getText().toString();
cfmalt.setMessage(editText.getText().toString()+"\n"+ vol_edit2.getText().toString());
cfmalt.setMessage(dt.getMonth())
//cfmalt.setMessage("Name:").setMessage(vol_edit2.getText().toString());
cfmalt.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
cfmalt.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
I am making an ALert Dialog with custom EditText Field.
I made a View variable and then associated it with my custom EditText field.
requestView = inflater.inflate(R.layout.send_request,null);
Then I added that view to my AlertDialog
alert.setView(requestView);
And after that I added the onClick Method To My Button to perform the alert Dialog action..
chatRequestbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alert.setPositiveButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
request = requestMsg.getText().toString();
send();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
}
});
It worked correctly. But after pressing cancel option on alert dialog when I press the button again to perform the alert dialog option.
It crashes with the following error.
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4417)
at android.view.ViewGroup.addView(ViewGroup.java:4258)
at android.view.ViewGroup.addView(ViewGroup.java:4230)
at android.support.v7.app.AlertController.setupCustomContent(AlertController.java:647)
at android.support.v7.app.AlertController.setupView(AlertController.java:463)
at android.support.v7.app.AlertController.installContent(AlertController.java:226)
at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
at android.app.Dialog.dispatchOnCreate(Dialog.java:395)
at android.app.Dialog.show(Dialog.java:294)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:955)
at com.buckydroid.anonchat.User$3.onClick(User.java:86)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22433)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6126)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I though making the view null and adding the view again while clicking on the button will fix the issue. But same problem again and again..
If you want to use an existing View, use this.
alert.setOnDismissListener(new OnDismissListener(){
((ViewGroup)requestView.getParent()).removeView(requestView);
});
I converted the above code from Kotlin to Java by hand, plz check before use.
Your problem is here:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setView(requestView);
In this case alertis not the dialog, but a builder. So every time when you're trying to show it - it rebuilds this dialog and trying to add same view for it - requestView. Because it is cached in the builder. To fix it - move
requestView = inflater.inflate(R.layout.send_request,null);
alert.setView(requestView);
to your OnClick method where you're showing the dialog. So it should look like this:
chatRequestbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
requestView = inflater.inflate(R.layout.send_request,null);
alert.setView(requestView);
alert.setPositiveButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
request = requestMsg.getText().toString();
send();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
}
});
You want to set an on dismiss listener. I did something like:
The dialog should set an on Dismiss listener
alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
((ViewGroup)requestView.getParent()).removeView(requestView);
}
});
I am trying to include an AlertDialog builder within a method that prompts for a pin code and when the positive button is pressed, checks it against a database value and returns a true or false value to the method caller.
For example: Adding/editing/deleting a user task requires a pin code. I don't want to generate a different AlertDialog for all three (and more) of these actions. I want to wrap the following code within a TaskService class that I can call from any activity, and react based on the result from within that activity.
So TaskService.java would have:
public boolean isCorrectPin(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
final EditText editText = new EditText(context);
builder.setView(editText);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (editText.getText().toString()) == getPinCode(){
//return true
}
}
});
builder.show();
}
and OpenTaskAdapter.java would have:
public void onBindViewHolder(ViewHolder holder, int position){
holder.btnMarkAsComplete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (service.isCorrectPin(v) {
//complete task
}
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (service.isCorrectPin(v) {
//delete task
}
}
});
It's important to note that these two button listeners could be in totally different activities.
You can create your own method to generate dialog with listener:
public void isCorrectPin(Context context, String title, String message, String btnPositive, final DialogSingleButtonListener dialogSingleButtonListener) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle(title);
dialogBuilder.setMessage(message);
dialogBuilder.setPositiveButton(btnPositive, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (editText.getText().toString() == getPinCode()){
dialogSingleButtonListener.onButtonClicked(dialog);
}
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
And the listener class:
public interface DialogSingleButtonListener {
public abstract void onButtonClicked(DialogInterface dialog);
}
And use it like:
service.isCorrectPin(context, title, message, btnPositive
new DialogSingleButtonListener() {
#Override
public void onButtonClicked(DialogInterface dialog) {
//code here is only called if they entered a correct pin.
}
}
);
A dialog can't "return" a value in the way that it looks like you're expecting. A dialog can make changes to some other object, but you can't have a bit of code block on it and wait for the user to finish interacting with it.
Instead, you'll need to set up listeners for when the prompt dialog is dismissed or buttons or clicked, or whatever other event signals that you have what you need from it. Those listeners can then read the data gathered and set by the dialog.
this is how i'm doing :
public Boolean showAlert(String message)
{
action = false;
AlertDialog.Builder alertDialog = new AlertDialog.Builder(HAActivity.this);
// Setting Dialog Title
alertDialog.setTitle(getString(R.string.app_name));
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Icon to Dialog
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
action = true;
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("Cancle", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
action = false;
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
return action;
}
and calling function like this :
//activity in which you create function
if (Activity.showAlert("Do you really want to delete ??"))
{
//delete it anyway.
}
Okay, so I wrote this code, where I use a thread to open some alert dialogs. The problem is that the thread doesn't wait for the first dialog to close before opening the second dialog. As you can see in the code I used wait() between opening the two dialogs and usenotify() in the onClick events of the buttons in the dialogs. I use the runOnUidThread() function to show the created dialogs. For some reason, when I open the activity the dialogs won't open and the app will have a black screen and the app will eventualy stop working. When I comment out the wait() statements (including the try and catch statements), the activity shows both the alert dialogs after each other. So is it even possible to wait for user input like this? Or am I doing something completly wrong. Thank you. HEre is my code :
public class EditTagActivity extends Activity
{
AlertDialog alertDialog1, alertDialog2;
Thread dialogManager = new Thread()
{
#Override
public void run()
{
runOnUiThread(showDialog1);
try
{
synchronized(dialogManager)
{
Log.d("Threads", "wait()");
dialogManager.wait();
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(showDialog2);
try
{
synchronized(dialogManager)
{
Log.d("Threads", "wait()");
dialogManager.wait();
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread showDialog1 = new Thread()
{
#Override
public void run()
{
Log.d("Threads", "alertDialog1.show();");
alertDialog1.show();
}
};
Thread showDialog2 = new Thread()
{
#Override
public void run()
{
Log.d("Threads", "alertDialog2.show();");
alertDialog2.show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_tag);
Log.d("Threads", "setup()");
setup();
}
void setup()
{
Log.d("Threads", "g.run()");
createAlertDialog();
dialogManager.run();
}
void createAlertDialog()
{
Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Alert");
alert.setMessage("Flaq");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
synchronized(dialogManager)
{
dialogManager.notifyAll();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
synchronized(dialogManager)
{
dialogManager.notifyAll();
}
}
});
alertDialog1 = alert.create();
alertDialog2 = alert.create();
}
}
Yes, just call the dialog.show() of the second dialog in the onClick of the first dialog's setPositiveButton. This way the second dialog will be forced to wait until the first one is dismissed.
Why are you using threads to wait for user input? A dialog has to be run on the UI-thread as stated in the android training guide: "Every app has its own special thread that runs UI objects such as View objects; this thread is called the UI thread."
A dialog will occupy the UI-thread until it is dismissed. On close you can process the user input on a background thread.
Here are some good references:
https://developer.android.com/training/multiple-threads/communicate-ui.html
http://developer.android.com/guide/topics/ui/dialogs.html
void createAlertDialog()
{
Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Alert");
alert.setMessage("Flaq");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
/*
Handle user input on other thread. With for example AsyncTask
*/
alertDialog2 = alert.create();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
/*
Handle user input on other thread. With for example AsyncTask
*/
}
});
alertDialog1 = alert.create();
}
I am new to Android, i am writing a program where when a user clicks a button a Alert Dialog to appear. This alert dialog has 2 buttons, Yes and No. Upon clicking Yes/No, i need to sysout the response.
The code i have so far; Can someone help me add the Alert Dialog;
public class HelloWorldProjectActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myFirstScreen);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==(R.id.button1)){
System.out.println("first button clicked");
// I need a Alert Dialog to appear here, and that will have 2 buttons YES and NO, the users response should be printed to the console.
}
}
You cannot System.out.print().
There are several methods to display the result. One is to use Toast. It will briefly show a text message and then disappear.
new AlertDialog.Builder(this)
.setMessage("Are you sure?")
.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(TestAndroidActivity.this, "YES CLICKED",
Toast.LENGTH_LONG).show();
}
}).setNegativeButton("No", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(TestAndroidActivity.this, "NO CLICKED",
Toast.LENGTH_LONG).show();
}
}).show();
Modify your code as follows:
The activity class doesn't have to implement OnClickListener.
Thus, remove onClick() method
Go to the layout file, add an attribute android:onClick="click" in the button declaration.
Add public void click(View view) with the previous code.
First of all, there really isn't any system.out to print to in android. What you should try instead is printing to the log. For information on how to print to the log, check this out. To then see the activity of the log (including messages you printed to it), checkout the logcat.
Second, for information on creating an alert dialog, please view this documentation.