Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edittext to String

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();
like image 998
daveeloo Avatar asked May 10 '11 07:05

daveeloo


People also ask

What is EditText?

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.

Can you set text in EditText?

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.


2 Answers

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
like image 57
2red13 Avatar answered Nov 15 '22 05:11

2red13


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

like image 22
Zoombie Avatar answered Nov 15 '22 05:11

Zoombie