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

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();
}
});

Related

Dynamically add Views in Dialog

I am trying to make Dialog that will consist 2x EditText and 1x Buttons. By clicking additional button you can add another 2x EditText and 1x Buttons. This 1x Button provide deleting this added pair. When i try to use button that should add another Views it's working properly. But button for deleting the View is working only for the first pairs. How can i do this with android:onClick, because i was trying buy it crashed.
Here is my code of Dialog class:
public class ExampleDialog extends AppCompatDialogFragment {
private EditText editTextUsername;
private EditText editTextPassword;
private ExampleDialogListener listener;
private LinearLayout parentLinearLayout;
private Context mContext;
Button dodaj,usun;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_template, null);
builder.setView(view)
.setTitle("Login")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();
listener.applyTexts(username, password);
}
});
editTextUsername = view.findViewById(R.id.edit_username);
editTextPassword = view.findViewById(R.id.edit_password);
parentLinearLayout = (LinearLayout) view.findViewById(R.id.parent_linear_layout);
dodaj = view.findViewById(R.id.add_field_button);
usun = view.findViewById(R.id.delete_button);
dodaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.field, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
}
});
usun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
parentLinearLayout.removeView((View) v.getParent());
usun = v.findViewById(R.id.delete_button);
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (ExampleDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
"must implement ExampleDialogListener");
}
}
public void contexta(Context context)
{
this.mContext = context;
}
public interface ExampleDialogListener {
void applyTexts(String username, String password);
}
}
And there is the conception of Dialog box on the picture below:
Picture
This issue may be due to view reference. Check whether v.getParent() is the view you want to delete or not.
For testing you can use "removeViewAt(int index)" method. Pass an index and check whether view is deleted at index or not.

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();
}
}
});

Dialog box inside tab group not firing

I am having a great difficulty on these part. I cannot call my dialog when I put my class inside Tab Group. Is there anyway I could do this?
This is my dialog creator
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
return createDialog();
default:
return null;
}
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case 1:
// Clear the input box.
EditText text = (EditText) dialog.findViewById(TEXT_ID);
text.setText(textme);
text.setKeyListener(null);
break;
}
}
private Dialog createDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(SpecialofMonth.this);
final EditText input = new EditText(this);
input.setId(TEXT_ID);
builder.setView(input);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
return builder.create();
}
Calling it on button click
View.OnClickListener handlesReadme = new View.OnClickListener() {
public void onClick(View v) {
showDialog(1);
}
};
This one works when it is outside the tab group. But in vice versa or when it is inside, it is not working..
Can you help me out?
in side your TAB Group create like this
AlertDialog.Builder builder = new AlertDialog.Builder(SpecialofMonth.this.getParent());

Android - retrieving text input from an alertbuilder dialog

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();
}

Categories