On the Android I'm trying to turn an Edittext
to a string. The toString()
method doesn't work, playerName is null when I print it out. Are there any other ways to turn an edittext to a string?
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("Your Name");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
playerName = input.getText().toString();
}
});
alert.show();
A EditText is an overlay over TextView that configures itself to be editable. It is the predefined subclass of TextView that includes rich editing capabilities.
In android, we can set the text of EditText control either while declaring it in Layout file or by using setText() method in Activity file.
the alertdialog looks fine, but maybe the error is located in the rest of the code. You have to keep in mind that you are not able to use the var playerName just beneth the show() of the dialog, if you want to print out the name you should do this with a runnable wich you call here:
static Handler handler = new Handler();
[.......]
public void onClick(DialogInterface dialog, int whichButton) {
playerName = input.getText().toString();
handler.post(set_playername);
}
[.......]
static Runnable set_playername = new Runnable(){
@Override
public void run() {
//printout your variable playerName wherever you want
}
};
edit to clarify:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("Your Name");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
playerName = input.getText().toString();
//call a unction/void which is using the public var playerName
}
});
alert.show();
// the variable playerName is NULL at this point
editText.getText().toString()
gives you a string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With