Rearchitecting the Prompt Dialog

Let us revisit the problematic code in the previous prompt-dialog implementation:

String reply = Alerts.showPrompt("Your text goes here", this);

As we have proved through the discussion, the value of the string variable reply will be null, because the prompt dialog initiated by Alerts.showPrompt() is incapable of returning a value on the same thread. The only way you can accomplish this is to have the activity implement the callback method directly and not rely on the PromptListener class. Get this done in the Activity class by implementing the OnClickListener:

public class SampleActivity extends Activity implements android.content.Dialoglnterface.OnClickListener {

other code if (item.getItemId() == Alerts.showPrompt("Your text goes here", this);

public void onClick(DialogInterface v, int buttonId)

//figure out a way here to read the reply string from the dialog

As you can see from this onClick callback method, you can correctly read the variables from the instantiated dialog because the user will have closed the dialog by the time this method is called.

It is perfectly legitimate to use dialogs this way. However, Android provides a supplemental mechanism to optimize performance by introducing managed dialogs—dialogs that are reused between multiple invocations. You'll still need to use callbacks when you work with managed dialogs, though. In fact, everything you've learned in implementing the prompt dialog will help you work with managed dialogs and understand the motivation behind them.

0 0

Post a comment