Returning A Value From AlertDialog - java

I want to build a function that creates an AlertDialog and returns the string that the user entered, this the function I have for creating the dialog, how do I return the value?
String m_Text = "";
private String openDialog(String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle(title);
final EditText input = new EditText(view.getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
// return string
}

The call builder.show() which opens your AlertDialog is not a blocking call, meaning the next instructions will be executed without waiting for the AlertDialog to finish (return). The way you should interact with it is by using some sort of callback. For instance, your OnClickListeners are an implementation of such a pattern.
A simple callback pattern
One clean way to achieve what you want is to create a Functional Interface which is an interface having only one method. You would use it for handling your callbacks.
Example
interface OnOK{
void onTextEntered(String text);
}
And then you would alter you method to be like:
private void openDialog(String title, final OnOK onOK) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle(title);
final EditText input = new EditText(view.getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Oi, look at this line!
onOK.onTextEntered(input.getText().toString());
}
});
builder.show();
}
You can use it like this:
openDialog("Title", new OnOK() {
#Override
onTextEntered(String text) {
Log.i("LOG", text);
}
});

This looks to me like you have stored the value of the inputted text in the m_Text field. You can either just return that field or have a variable within the function in which you store the value to be returned.
Where you have:
//Return string
simply replacing with:
return m_Text;
should do the job.

Create another method in the same class that accepts a string value, then call that function providing the value of input.getText().toString() from your setPositiveButton onclick event

Related

How to show AlertDialog even if Activity is on background?

I have an AlertDialog and I want to show it even if the user is visiting another activity.
This is AlertDialog:
AlertDialog.Builder builder = new AlertDialog.Builder(context.getApplicationContext());
builder.setMessage("Message").setCancelable(
false).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alert = builder.create();
alert.show();
You can create a method in utils class and pass context, so that you can use dialog in required class, but precaution need to take with life cycles to avoid memory leaks.

Dealing with userInput from AlertDialog on android Studio

Currently struggling to handle the user input from my AlertDialog box. Everything works fine, but I don't know what to do with the user input in order to save it and access it within another function.
private void promptUser() {
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText promptTitle = new EditText(this);
promptTitle.setHint("Title");
layout.addView(promptTitle);
userPrompt = new AlertDialog.Builder(this);
userPrompt.setView(layout);
userPrompt.setTitle("Enter map information").setView(layout);
userPrompt.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog", "Create button was hit");
Log.i("AlertDialog", "This is the text that was entered:" + promptTitle.getText().toString());
userInputs = promptTitle.getText().toString();
}
});
userPrompt.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog", "Cancel button was hit");
}
});
userPrompt.show();
}
and where I call the function:
public void onMapClick( LatLng point ) {
promptUser()
//Log.d(userInputs.get(0), "COOL");
}
The main error I'm encountering is that after calling my method promptUser(), everything runs but the next several lines of code don't wait for the user to click the PositiveButton. e.g, my Log shows "User inputs: null", since tempString isn't yet available. How can I make my function wait until the user has hit submit before running the next line of code?
Put the call to onMapClick inside the positive button callback.
userPrompt.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
userInputs = promptTitle.getText().toString();
onMapClick();
}
});
It's a bit hard to tell if this is exactly what you want since you haven't provided enough code, but this is what you asked for.

Assign value to variable using popup edit text on android studio

I'm trying to make a popup box with edit text field on Android Studio and would like to store the data entered by the user in a variable used in that class.
Something like this:
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
name = input.getText().toString(); //<---HERE !want to use this variable
}
})
.setNegativeButton("Cancel", null)
.show();
This doesn't work, so how could I extract the value of name from my popup window to use it in the main code?
Do it this way:
final String[] name = new String[1];
final EditText input = new EditText(this);
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
name[0] = input.getText().toString(); <---HERE! want to use this variable
}
})
.setNegativeButton("Cancel", null)
.show();
Access it using name[0]
Clarification for the followup question by Jox in the comment below: To access the variable inside onClick it needs to be final. But, you cannot assign a value to a simple final variable. However, you can assign a value to a Array member. Hence, the array and not a string variable. Btw, Andriod Studio will do it for you this way itself, just follow the suggested fixes for erroring-out code.
You should declare the DialogInterface.OnCLickListener inside of your Activity. By either creating a listener and assingning it or having your activity implement the interface. And then you won't need to declare name as final.
The reason you have to declare name as final is because you're anonmously creating an object to listen to the click, which require a contract of anything external being used by this anonymous class must be declared as final.
I would recommend creating a listener in your Activity and then assign it to the setOnClickListener(x)
Try this, it works for me :
public class Activity extends AppCompatActivity implements DialogInterface.OnClickListener {
private EditText input;
private String str = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
input = new EditText(this);
}
public void onClickAlert(View v) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", this)
.setNegativeButton("Cancel", null)
.show();
//variable str still equal to "" here
}
#Override
public void onClick(DialogInterface dialog, int which) {
str = input.getText().toString(); /*<---HERE! want to use this variable*/
//use it here
Log.d("Activity", "User input : " + str);
}
}
Implement the OnClickListener in your Activity and read the value of the text field in the callback fonction.

System Exit if dialog textfield matches private text field

I have implemented a dialog box, I also get the text field as a string. Now the problem I have is that I want to compare the text input to a String and exit the app if the text on the dialog box matches either a string under (R.strings.stringname) or either a private String variable.
I have implemented this code but it does not seem to work.
public void onBackPressed(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setIcon(R.drawable.ic_about_logo);
alert.setTitle("Phoebus Club");
alert.setMessage("Please Insert Security Key");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
securityKey = input.getText().toString();
if(securityKey == "oneplc"){
System.exit(0);
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
Have a look at this question
The == operator doesn't really compare values, rather reference equality. You should use the equals() method of the String object instead:
if(securityKey.equels("oneplc")){
System.exit(0);
}
if static string then instead of
securityKey == "oneplc"
do
securityKey.equals("oneplc");
if from strings.xml then
securityKey.equals(getResources().getString(R.string.stringname));

alert box in android is not working

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

Categories