Android - retrieving text input from an alertbuilder dialog - java

I've got a View defined in an xml file. It contains two Edittext fields (amongt other things like text)
I use an AlertBuilder to trigger a dialog where a user enters text(such as username and pass) into both edittext fields. When I try to retrieve the strings and send them to Login(), both strings are just null. What is going on?
It seems like somehow the string data isn't saved?
Here's when I show the Dialog in my app:
SignInDialog.show(ScreenMain.this,
"Login",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
LayoutInflater inflater = (LayoutInflater) ScreenMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screen_dialog_login, null);
LogIn(((EditText) layout.findViewById(R.id.screen_dialog_login_username_edit)).getText().toString(),
((EditText) layout.findViewById(R.id.screen_dialog_login_password_edit)).getText().toString());
}
},
"Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
Here's a class I use to instantiate a Dialog:
/* login dialog*/
static class SignInDialog {
public static void show(Context context, String positiveText, DialogInterface.OnClickListener positive, String negativeText, DialogInterface.OnClickListener negative){
AlertDialog.Builder builder;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screen_dialog_login, null);
builder = new AlertDialog.Builder(context);
builder.setView(layout);
if(positive != null && positiveText != null){
builder.setPositiveButton(positiveText, positive);
}
if(negative != null && negativeText != null){
builder.setNegativeButton(negativeText, negative);
}
builder.create().show();
}
}

To inflate a layout is to create a new instance of it. (You're not receiving a reference to an existing instance.) So, in your onClick you are creating a new copy of the layout and your fields don't contain any text because they are not the same ones your user just entered text in.

Why not just completely subclass AlertDialog.Builder and add a method to retrieve the EditText values?

Do something like:
View layout = inflater.inflate(R.layout.screen_dialog_login, null);
layout.findViewById(R.id.*yourwidget*);
i tried it and it helped

Here is the method I am using:
private void showPopUp3() {
AlertDialog.Builder helpBuilder = new AlertDialog.Builder(AlarmReceiverActivity.this);
helpBuilder.setTitle("hi");
// helpBuilder.setMessage("This is a Simple Pop Up");
final EditText input = new EditText(this);
input.setHeight(20);
input.setText("");
LayoutInflater inflater = getLayoutInflater();
final View checkboxLayout = inflater.inflate(R.layout.alarm, null);
checkboxLayout.findViewById(R.id.Yes).setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// setTitle("button2");
checkboxLayout.findViewById(R.id.note).setVisibility(View.VISIBLE);
}
});
checkboxLayout.findViewById(R.id.No).setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// setTitle("button2");
checkboxLayout.findViewById(R.id.note).setVisibility(View.INVISIBLE);
}
});
helpBuilder.setView(checkboxLayout);
helpBuilder.setPositiveButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
mMediaPlayer.stop();
finish();
}
});
helpBuilder.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
mMediaPlayer.stop();
//showSimplePopUp();
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog = helpBuilder.create();
helpDialog.show();
}

Related

Android: What is the best practice to organize methods to show alert dialog

I am beginner in Android development. Suppose I have some methods to show AlertDialog within an Activity. But each AlertDialog behavior is slightly different. What is the best practice to organize the methods to show AlertDiaolog?
code is like this.
private void showNumberPickerDialog() {
LayoutInflater inflater = this.getLayoutInflater();
View numberPickerDialogView = inflater.inflate(R.layout.number_picker, null);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Title for number picker here");
alertDialog.setCancelable(false);
alertDialog.setView(numberPickerDialogView);
final NumberPicker numberPicker = roomSizeNumberDialogView.findViewById(R.id.number_picker);
numberPicker.setMaxValue(10);
numberPicker.setMinValue(0);
numberPicker.setWrapSelectorWheel(false);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Something here
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private void showMessageDialog(final boolean isA) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Title here");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (isA) {
doA();
} else {
doB();
}
}
});
alertDialog.show();
}
private void showAlertDialogC() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
final EditText inputEditText = new EditText(this);
inputEditText.setInputType(InputType.TYPE_CLASS_TEXT);
innputEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
alertDialog.setTitle("Title here");
alertDialog.setCancelable(false);
alertDialog.setView(nameEditText);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do something here
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
Is there a good way to organize the parts like this?
You can also use a customizable dialog if that's what you are looking for.
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_options);
dialog.show();
TextView tvDelete = dialog.findViewById(R.id.tvDelete);
tvDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Dialog deleteDialog = new Dialog(context);
deleteDialog.setContentView(R.layout.dialog_delete);
deleteDialog.show();
}
});
Treat it just like you would treat an activity. Set onClickListeners on the views for which you want some particular actions. I believe this custom dialog is much more flexible than the AlertDialog
I like to handle my dialog in a separate class, that way you have more control over everything - clickListners, layout design, etc... and you don't have tons of code lines in your activity.
For example, create dialogClass:
public class ProgressDialog extends Dialog {
public ProgressDialog(#NonNull Context context) {
super(context);
setContentView(R.layout.progress_dialog); //this is your layout for the dialog
}
}
And all you need to do is to create dialog instant and call it like this:
ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.show(); // this line shows your dialog

Prevent AlertDialog from closing when EditText is empty

So without having to create a custom dialog as I currently have a number of dialog layouts and don't want to have to do it for each one, is there a way to prevent this dialog from closing when the positive button is pressed and the EditText is empty?
Currently it closes the dialog every time I hit enter and there is nothing in the EditText field.
public AlertDialog webpageDialog() {
AlertDialog.Builder webpageDialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
webpageDialogBuilder.setView(inflater.inflate(R.layout.dialog_webpage, null))
.setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog webpageDialog = webpageDialogBuilder.create();
webpageDialog.setButton(DialogInterface.BUTTON_POSITIVE, context.getString(R.string.enter), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
EditText webpageInput = (EditText) webpageDialog.findViewById(R.id.dw_et_webpage_address);
Log.d(TAG, "Positive on click");
if(TextUtils.isEmpty(webpageInput.getText().toString())){
Log.d(TAG, "Edit text empty");
webpageInput.setError(context.getString(R.string.error_web_required));
} else {
Log.d(TAG, "Edit text not empty");
ms.setUriString("http://" + webpageInput.getText().toString());
ms.returnWithResult(1);
dialog.cancel();
}
Log.d(TAG, "Returning");
}
});
Log.d(TAG, "Returning dialog");
return webpageDialog;
}
this is how I'm doing it.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
EditText yourEditText = new EditText(this);
layout.addView(yourEditText);
builder.setView(layout);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ("".equals(yourEditText.getText().toString().trim())) {
//this will stop your dialog from closing
yourEditText.setError("This field is required!");
return;
}
//you logic here
dialog.dismiss();
}
});
I hope following line can help,
webpageDialogBuilder.setCancelable(false);

How can I see the text that I'm typing in editText window in alertDialog?

I have the following code for an AlertDialog window in which I want the user to input a number(that I'm storing in int m_Text). I have 2 problems: I can't see the numbers that I'm typing and if I press enter without any numbers it will crash. How can I solve them ? (the method pressMe() is executed when I press a button)
public void pressMe(){
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER );
AlertDialog.Builder myAlert = new AlertDialog.Builder(this);
myAlert.setMessage("Enter number:")
.setView(input)
.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = Integer.parseInt(input.getText().toString());
Log.d(TAG," Number : "+m_Text");
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setTitle("Test")
.setIcon(R.drawable.ic_launcher)
.create();
myAlert.show();
}
The answer why your application is crashed is here:
Integer.parseInt(input.getText().toString());
When input text is empty you try to parse "" on Integer and you get NumberFormatException.
you have to handle this situation for example like in code below:
final String str = input.getText().toString().trim();
m_Text = str.length() == 0 ? 0 : Integer.parseInt(str);
or
final String str = input.getText().toString().trim();
if(str.length() != 0){
m_Text = Integer.parseInt(str);
}
I don't understand your first problem. If you explain it to me, I help you.
Update
When I tried your code I have result like below:
Read this document
http://developer.android.com/guide/topics/ui/dialogs.html
if you want to use any types of dialog in your application.
1)Create a class that will extend DialogFragment class.
2)Overide onCreateDialog() method and inside that write your code for both Positive button and negative button
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
3)Call that Fragment from HostActivity using this code
DialogFragment newFragment = new YourFragmentClass();
newFragment.show(getSupportFragmentManager(), "missiles");
if you want a CustomLayout then
1)create a XML file in res->customLayout.xml and inside that place the view you want(In your case draw a Single EditText on that layout),do not add Button for Positive or Negative Button they are already add by DialogFragment.
2)Inside onCreateDialog() of dialogFragment do something like this
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
final EditText et_text=(EditText)getActivity().findViewById(R.id.editTextId);
builder.setView(inflater.inflate(R.layout.custom_layout, null))
// Add action buttons
.setPositiveButton(R.string.send, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String mob=et_text.getText().toString();
//Do What you want to do with EditText
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Coding for Negative Button Here
}
});
return builder.create();
}
you can Pass EventBack to Hosting Activity.
Read reference document
Hope this will help you

Android - Can't get value from EditText inside Custom Dialog

I have been unsuccessful in getting the input from my EditText object inside my custom dialog.
public class SetCityDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
final View view = factory.inflate(R.layout.city_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.city_dialog, null))
// Add action buttons
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//This is the input I can't get text from
EditText inputTemp = (EditText) view.findViewById(R.id.search_input_text);
//query is of the String type
query = inputTemp.getText().toString();
newQuery();
getJSON newData = new getJSON();
newData.execute("Test");
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
SetCityDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
I don't get any exceptions, but the variable query is set to an empty string.
Any help would be fantastic.
I was trying to do the same thing and i get the same error. I don't no why. I already use AlertDialog.Builder in the past and get no trouble. But in your case change this code:
public void onClick(DialogInterface dialog,
int id) {
//This is the input I can't get text from
EditText inputTemp = (EditText) view.findViewById(R.id.search_input_text);
//query is of the String type
query = inputTemp.getText().toString();
newQuery();
getJSON newData = new getJSON();
newData.execute("Test");
}
By this one:
public void onClick(DialogInterface dialog,
int id) {
Dialog f = (Dialog) dialog;
//This is the input I can't get text from
EditText inputTemp = (EditText) f.findViewById(R.id.search_input_text);
query = inputTemp.getText().toString();
...
}
This solution works for me and it seems to be the same for you.
Found on stackoverflow
Use this instead :
View myLayout = nflater.inflate(R.layout.city_dialog, null);
EditText myEditText = (EditText) myLayout.findViewById(R.id.myEditText);
String valueOfEditText = myEditText.getText().toString();
No need to do that much coding. just change
builder.setView(inflater.inflate(R.layout.city_dialog, null))
to
builder.setView(view)
and access text of EditText using **view.findView.....
EditText inputTemp = (EditText) view.findViewById(R.id.search_input_text);
String xyz = inputTemp.getText().toString();
This is worked for me:
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Dialog inDialog = (Dialog) dialog;
EditText emailAddress = (EditText) inDialog.findViewById(R.id.emailAddress);
email = emailAddress.getText().toString();
if(email.length() == 0) {
objPublicDelegate.showToast("Please fill Email Address.");
}else{
objLoadingDialog.show("Please wait...");
// Call a network thread Async task
mNetworkMaster.runForgetAsync(email);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});

Android: How do I retrieve Edittext.getText() in custom AlertDialog?

The topic explains what i'm after... I can't retrieve the EditText from my custom view in android. All I get is a Nullpointer Exception. :/
I've marked where the problems are in the code with comments.
The ID:s are correct and my XML layout is a simple RelativeLayout containing two EditText attributes.
Obviously I'm missing something trivial here, but I've now stared at the code for almost 2 hours without solving this, so I thought I'll give SO a try instead.
protected void showLoginDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.activity_login, null))
// Add action buttons
.setPositiveButton(R.string.login, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
/* ERROR HERE! */
EditText uName, passWord;
uName = (EditText) findViewById(R.id.login_username);
passWord = (EditText) findViewById(R.id.login_password);
Log.i(TAG, uName.getText().toString() + " " + passWord.getText().toString());
/* STOP */
if(the_view.getSocketTask().isConnected) {
the_view.getSocketTask().send_command("LOGIN ");
} else {
showToast("Not connected!");
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create().show();
}
EDIT:
After suggestions the following code is a working one! Thanks again!
protected void showLoginDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.activity_login, null))
// Add action buttons
.setPositiveButton(R.string.login, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Dialog f = (Dialog) dialog;
/* ERROR HERE! */
EditText uName, passWord;
uName = (EditText) f.findViewById(R.id.login_username);
passWord = (EditText) f.findViewById(R.id.login_password);
Log.i(TAG, uName.getText().toString() + " " + passWord.getText().toString());
/* STOP */
if(the_view.getSocketTask().isConnected) {
the_view.getSocketTask().send_command("LOGIN ");
} else {
showToast("Not connected!");
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create().show();
}
Thanks in advance!
Alex
Cast the Dialog as a View:
View v_iew=inflater.inflate(R.layout.activity_login, null)) ;
builder.setView(v_iew);
Then replace:
uName = (EditText) findViewById(R.id.login_username);
passWord = (EditText) findViewById(R.id.login_password);
with
uName = (EditText) v_iew.findViewById(R.id.login_username);
passWord = (EditText) v_iew.findViewById(R.id.login_password);
(Can't vote so creating new answer: Took me hours to figure this out; adding the qualifier finally fixed it - like you figure out already)
Doesnt work:
final Dialog dialog = new Dialog(this);
...
keyInput = (EditText) findViewById(R.id.key_input);
Works:
final Dialog dialog = new Dialog(this);
...
keyInput = (EditText) dialog.findViewById(R.id.key_input);
In the case of an EditText you should implement TextWatcher It is generally a very bad idea to use editText.getText()
Here is a very simple example code for Custom Dialog containing an EditText as part of the layout. There is also a button that needs to be on the same layout which when clicked will show you the text which you just entered. Have fun!
final String inputString = null;
final Dialog dialog = new Dialog(YourActivityName.this);
dialog.setContentView(R.layout.custom_dialog_layout);
EditText editText = (EditText) dialog.findViewById(R.id.id_of_edit_text);
Button done = (Button) dialog.findViewById(R.id.done);
dialog.show();
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
inputString = s.toString();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(YourActivityName.this, inputString, Toast.LENGTH_SHORT);
dialog.dismiss();
}
});

Categories