Edittext to String

On Android, I am trying to turn Edittextinto a string. The method toString()does not work, playerName is null when I print it. Are there other ways to turn edittext into 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();
+3
source share
5 answers

alertdialog looks good, but maybe the error is in the rest of the code. You should keep in mind that you cannot use var playerName, just run the show () dialog box if you want to print the name you need to make using runnable, which 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
+6
source

editText.getText().toString() gives a string

+5
source

EditText

et = (EditText)findViewById(R.id.resource_id_of_edittext);
String text = et.getText().toString();`
+3
String mystring=input.getText().toString();
+2

If playerNamedeclared as String, you do not need to drop it or anything else. The method getTextgives you CharSequencewhich you can use as String.

The problem is that you are creating the variable inputfrom scratch, so it will not refer to existing ones View. You should do something like:

EditText input = findViewById(R.id.player);

And then you can:

playerName = input.getText();
0
source

All Articles