Execution doesn't wait to Alertdialog.dismiss() - java

I'm developing an Android application and I have this question:
How can I do to make execution waits until user has selected an option from an AlertDialog?
This is my code:
if (mPerson== null)
{
mPerson = new Person();
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.dialog_message_select))
.setTitle(getString(R.string.dialog_title_attention));
builder.setPositiveButton(R.string.male, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
mPerson.setGender(Gender.male);
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.female, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int arg1)
{
mPerson.setGender(Gender.female);
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
// TODO: Show data.
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
After dialog.dismiss() I have to execute this:
// TODO: Show data.
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();

Do the following:
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.dialog_message_select))
.setTitle(getString(R.string.dialog_title_attention));
builder.setPositiveButton(R.string.male, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
mPerson.setGender(Gender.male);
dialog.dismiss();
postSelection();
}
});
builder.setNegativeButton(R.string.female, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int arg1)
{
mPerson.setGender(Gender.female);
dialog.dismiss();
postSelection();
}
});
dialog = builder.create();
dialog.show();
}
Call this method once the selection is complete.
public void postSelection(){
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
}

Think in terms of event based execution. If you want some code to execute when you press a button, then wire it to do so. Place the code in question in a method that you can call whenever you want.
Generally, when you are programming on Android, you need to adhere to the event based nature of the platform. Traditional procedural sequential thinking will lead you to dead ends.

You have to customize your dialog interface like this .
You should use onDismissListener on dialog interface.Dont make it anonymous.
private class MyDialogInterfaceMethod implements DialogInterface.OnClickListener,DialogInterface.OnDismissListener
{
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//when user click a button
}
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
//put your code here
}
}
Than use it on your alert dialog like this
builder.setNegativeButton("CANCEL",new MyDialogInterfaceMethod ());

Related

How to check Alert Dialog visibility?

I want to check alert dialog is visible or not. In most post I saw that they used isShowing, but seems like its not describable now.
When user click info textview, I pause music. If user close alert dialog, music will be play again.
info_Button.setClickable(true);
info_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaControl.pause();
AlertDialog.Builder playstopbutton_builder = new AlertDialog.Builder(exercise_arm_triceps_execute.this);
playstopbutton_builder.setTitle("WARNING").setMessage("Please get warm before exercising!");
playstopbutton_builder.create().show();
playstopbutton_builder.setCancelable(false);
//if alert dialog is visible keep music paused
//else if mediaControl.start();
}
});
since you have made Cancelable false, you might need to use
for positive button say like a okay
playstopbutton_builder.setPositiveButton(positiveBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
})
for negative button say like a cancel
playstopbutton_builder.setNegativeButton(negativeBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
})
so it would look like this
info_Button.setClickable(true);
info_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaControl.pause();
AlertDialog.Builder playstopbutton_builder = new AlertDialog.Builder(exercise_arm_triceps_execute.this);
playstopbutton_builder.setTitle("WARNING").setMessage("Please get warm before exercising!");
playstopbutton_builder.create().show();
playstopbutton_builder.setCancelable(false);
playstopbutton_builder.setPositiveButton(positiveBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
});
playstopbutton_builder.setNegativeButton(negativeBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
});
}
});
You need to check dialog show or not change you code like this.
info_Button.setClickable(true);
info_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaControl.pause();
AlertDialog.Builder playstopbutton_builder = new AlertDialog.Builder(exercise_arm_triceps_execute.this);
playstopbutton_builder.setTitle("WARNING").setMessage("Please get warm before exercising!");
playstopbutton_builder.create();
playstopbutton_builder.setCancelable(false);
//if alert dialog is visible keep music paused
//else if mediaControl.start();
if(!playstopbutton_builder.isShowing()){
//if its visibility is not showing then show here
playstopbutton_builder.show();
}else{
//do something here... if already showing
}
}
});
You may want to add an OnDismissListener to the playstopbutton_builder:
playstopbutton_builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mediaControl.start();
}
});
This way, when the user dismisses the Alert Dialog, the music will start to play again.
EDIT: if the OnDismissListener approach is not desired, maybe something like this would be better:
public void infoClickHandler(View v) {
mediaControl.pause();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setMessage("restart the music?");
b.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mediaControl.start();
}
});
b.show();
}
EDIT 2: On the other hand, if the dialog cannot have positive or negative buttons, and you do not want to set cancellable to false, this seems to work:
public void infoClickHandler(View v) {
mediaControl.pause();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setMessage("restart the music?");
b.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if (!mediaControl.isPlaying()) {
mediaControl.start();
}
}
});
b.show();
}
The OnDismissListener will be called when the user clicks outside of the dialog box.

java android return method within listener?

I am kind of new in Java Android, and Im facing this problem and i don't know what it's called, here is my code:
public boolean msgBox(String title, String text) {
boolean bReturn = false;
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setCancelable(false);
adb.setTitle(title);
adb.setMessage(text);
adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//this suppose tell msgBox return true
}
});
adb.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//this suppose tell msgBox return false
}
});
adb.show();
return bReturn;
}
Now how do I tell msgBox to return true / false when user clicked positive / negative button? thanks before
This is not possible, because the method will end after the Dialog is opened. The Dialog will continue to be open after the method is finished.
In order to return information back to your msgBox caller, you will need to provide a callback function.
You can create an interface, pass that into msgBox, and call it in your Dialog button.
public interface OnDialogButtonClickedCallback {
public void onDialogButtonClicked(boolean wasPositive);
}
Pass it in like this:
public boolean msgBox(String title, String text, final OnDialogButtonClickedCallback callback)
Use it in the button like this:
#Override
public void onClick(DialogInterface dialog, int which) {
if(callback != null) {
callback.onDialogButtonClicked(true);
}
}
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == 1) {
bReturn = true or false;//yes or no
}
//this suppose tell msgBox return false
}
In the function above you determine which button was clicked by variable int which (f.e.: Yes is first, No is second).
bReturn should be global.
Since you are doing separate listeners for each button, you don't even have to distinguish, since those are separate listeners.

Dialogue box does not show up

I am creating a dialogue box that should appear to the user in case of the GPS service is disabled. But what is happening is, although I disabled the service manually to force the dialogue appear, the App starts and nothing is happening.
The code below shows how I tried to create the dialogue box and when. Please let me know if there is any mistake.
JavaCode:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gpstest00);
locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
gpsEnable = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnable) {
showGPSDialogueBox();
}
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this.locationListener);
}
/*if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}*/
private void showGPSDialogueBox() {
AlertDialog.Builder alertDialogue = new AlertDialog.Builder(this);
alertDialogue.setTitle("GPS Settings");
alertDialogue.setMessage("GPS is deactivated. Do you want to switch " + to settings menu to activate it?");
alertDialogue.setPositiveButton("Settings",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialogue.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
}// Enf of showDialogueBox function.
You need to call show function for the dialog box to show
alertDialogue.show();
You need to create AlertDialog from AlertDialog.Builder object then show the AlertDialog using show() method as follows...
AlertDialog dialog = alertDialogue.create();
dialog.show();
Update your showGPSDialogueBox() as below...
private void showGPSDialogueBox() {
AlertDialog.Builder alertDialogue = new AlertDialog.Builder(this);
alertDialogue.setTitle("GPS Settings");
alertDialogue.setMessage("GPS is deactivated. Do you want to switch " +
" to settings menu to activate it?");
alertDialogue.setPositiveButton("Settings",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialogue.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog dialog = alertDialogue.create();
dialog.show();
}

How to show ProgressDialog after AlertDialog

I am having trouble with an alert dialog that I cannot hide.
when the user press a button I show a dialog that is created with this code :
new AlertDialog.Builder(this)
.setTitle(R.string.enterPassword)
.setView(textEntryView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = pwdText.getText().toString();
dialog.dismiss();
processUserAction(password,targetUri);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.
create();
There are some heavy operations performed in the 'processUserAction' method, and inside it I am using an AysncTask that displays a ProgressDialog.
The problem I am having is that the dialog prompting for the password never goes of the screen (I have tried with dismiss(), cancel()).
I guess it stays there until the onClick method is finished.
So, my question is how to close that AlertDialog, so I can show the ProgressDialog?
Another approach I have been trying is to set a DismissListener in the AlertDialog and calling the heavy operations from there, but I have had no luck ( it didn't get called ).
EDIT: Adding AsyncTask code
public class BkgCryptOperations extends AsyncTask<File,Void,Integer>{
#Override
protected Integer doInBackground(File... files) {
if (files!=null && files.length > 0){
File source = files[0];
File target = files[1];
return cryptAction.process(source,password, target);
}
return Constants.RetCodeKO;
}
CryptAction cryptAction;
String password;
ProgressDialog progressDialog;
public BkgCryptOperations (CryptAction cryptAction,String password,ProgressDialog progressDialog){
this.cryptAction=cryptAction;
this.password=password;
this.progressDialog=progressDialog;
}
#Override
protected void onPreExecute() {
if (progressDialog!=null){
progressDialog.show();
}
}
protected void onPostExecute(Integer i) {
if (progressDialog!=null){
progressDialog.dismiss();
}
}
}
Thanks in advance
Here is a excample how I do it:
public void daten_remove_on_click(View button) {
// Nachfragen
if (spinadapter.getCount() > 0) {
AlertDialog Result = new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(getString(R.string.dialog_data_remove_titel))
.setMessage(getString(R.string.dialog_data_remove_text))
.setNegativeButton(getString(R.string.dialog_no),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
// Nicht löschen
dialogInterface.cancel();
}
})
.setPositiveButton(getString(R.string.dialog_yes),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
String _quellenName = myCursor.getString(1);
deleteQuellenRecord(_quellenName);
zuletztGelöscht = _quellenName;
}
}).show();
} else {
// Keine Daten mehr vorhanden
Toast toast = Toast.makeText(Daten.this,
getString(R.string.dialog_data_remove_empty),
Toast.LENGTH_SHORT);
toast.show();
}
}
Here is the code of deleteQuellenRecord:
private void deleteQuellenRecord(String _quellenName) {
String DialogTitel = getString(R.string.daten_delete_titel);
String DialogText = getString(R.string.daten_delete_text);
// Dialogdefinition Prograssbar
dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// set the maximum value
dialog.setMax(4);
// display the progressbar
increment = 1;
dialog.show();
// Thread starten
new Thread(new MyDeleteDataThread(_quellenName)) {
#Override
public void run() {
try {
// Datensatz löschen
myDB.execSQL("DELETE ... ');");
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...);");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...;");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
// Einstellung speichern
try {
settings.edit().putString("LetzteQuelle", "-1")
.commit();
} catch (Exception ex) {
settings.edit().putString("LetzteQuelle", "").commit();
}
} catch (Exception ex) {
// Wait dialog beenden
dialog.dismiss();
Log.e("Glutenfrei Viewer",
"Error in activity MAIN - remove data", ex); // log
// the
// error
}
// Wait dialog beenden
dialog.dismiss();
}
}.start();
this.onCreate(null);
}
Wiht Async Task I do it this way:
private class RunningAlternativSearch extends
AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(SearchResult.this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
#Override
protected void onPreExecute() {
alternativeSucheBeendet = false;
String DialogTitel = getString(R.string.daten_wait_titel);
DialogText = getString(R.string.dialog_alternativ_text);
DialogZweiteChance = getString(R.string.dialog_zweite_chance);
DialogDritteChance = getString(R.string.dialog_dritte_chance);
sucheNach = getString(R.string.dialog_suche_nach);
dialog.setCancelable(true);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub
cancleBarcodeWorker();
if (alternativeSucheBeendet==false){
// Activity nur beenden wenn die Suche
// nicht beendet wurde, also vom User abgebrochen
Toast toast = Toast.makeText(SearchResult.this, SearchResult.this
.getString(R.string.toast_suche_abgebrochen),
Toast.LENGTH_LONG);
toast.show();
myDB.close();
SearchResult.this.finish();
}
}
});
dialog.show();
}
...
Can you show the code for processUserAction(..)? There is no need to include the dismiss.
I did something very similar and had no problems...
Here's the code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Export data.\nContinue?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String file = getObra().getNome();
d = new ProgressDialog(MenuActivity.this);
d.setTitle("Exporting...");
d.setMessage("please wait...");
d.setIndeterminate(true);
d.setCancelable(false);
d.show();
export(file);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
In export(file) I open the thread:
private void export(final String file) {
new Thread() {
public void run() {
try {
ExportData ede = new ExportData(
getApplicationContext(), getPmo().getId(),
file);
ede.export();
handlerMessage("Done!!");
} catch (Exception e) {
handlerMessage(e.getMessage());
System.out.println("ERROR!!!" + e.getMessage());
}
}
}.start();
}
In handlerMessage I dismiss the progressDialog and show the final message.
Hope it helps you.
You could create a listener outside of the AlertDialog, to abstract out the logic within the OnClickListener for the positive button. That way, the listener can be notified, and the AlertDialog will be dismissed immediately. Then, whatever processing of the user's input from the AlertDialog can take place independently of the AlertDialog. I'm not sure if this is the best way to accomplish this or not, but it's worked well for me in the past.
As far as I can tell, I don't see any obvious problems with your AsyncTask code.
public interface IPasswordListener {
public void onReceivePassword(String password);
}
IPasswordListener m_passwordListener = new IPasswordListener {
#Override
public void onReceivePassword(String password) {
processUserAction(password,targetUri);
}
}
public void showPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.enterPassword);
builder.setView(textEntryView);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
m_passwordListener.onReceivePassword(pwdText.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
}

How to return value from new object instance method declaration (nested)?

Ok this is the code:
public boolean alertDialog(String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TestBedAppActivity.this.agree = true;
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
TestBedAppActivity.this.agree = false;
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Inside the setPositiveButton() methos there is a nested declaration of the method onClick(). I want to return the boolean result for the main method alertDialog(String message) but I cannot do it. What am I missing? Help!!!!!!!
onClick runs when the user click the positive button or the cancel button. When you call "alert.show()", this method returns at once. So you don't know return what since the user operation does not happen.

Categories

Resources