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();
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
Here's how you get the text out of a EditText
et = (EditText)findViewById(R.id.resource_id_of_edittext);
String text = et.getText().toString();
String mystring=input.getText().toString();
If playerName
is declared as a String
, you shouldn't need to cast it or anything. The getText
method gives you a CharSequence
which you can use as a String
.
The issue is you're creating your input
variable "from the scratch" so it will not make reference to any existing View
. You should do something like:
EditText input = findViewById(R.id.player);
And then you can:
playerName = input.getText();
精彩评论