Show a string in an AlertDialog

0

Well, I'm learning android, I do not know much. In this application, so far I just want to display the value of "name" in the .setMessage of AlertDialog, and I'm not sure how I do it, grateful now!

NOTE: When I run the app on my device, "Your name is: android.support.v7.widget.AppCompatEditText {...}"

package usuario.app.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.*;
import android.app.*;
import android.view.*;


public class ComprasActivity extends AppCompatActivity {

EditText nome, idade,cidade;
Button enviar;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compras);

    nome    = (EditText) findViewById(R.id.nome);
    idade   = (EditText) findViewById(R.id.idade);
    cidade  = (EditText) findViewById(R.id.cidade);
    enviar = (Button)findViewById(R.id.enviar);

    enviar.setOnClickListener(new View.OnClickListener()
    {
                @Override
                public void onClick(View arg0)
                {
                    AlertDialog.Builder dialogo = new AlertDialog.Builder(ComprasActivity.this);
                    dialogo.setTitle("Seu perfil");
                    dialogo.setMessage("Seu nome é:" + nome);
                    dialogo.setNeutralButton("OK",null);
                    dialogo.show();
                }
    });
}

}

    
asked by anonymous 08.07.2017 / 17:24

1 answer

4

The variable nome is of type EditText , which represents an element of the layout. To access the text it contains it is necessary to call the method getText() :

dialogo.setMessage("Seu nome é:" + nome.getText());

It is important to point out that the getText() method returns the text in the form of charSequence and not String , which although in this case it is simple to work, in others that you find later you may no longer work.

To get the text of a EditText as String , you should use:

nome.getText().toString()

An example of this would be what the ramaral indicated, of assigning the text of EditText to a variable of type String . In this case it would have to be:

String nomeRecolhido = nome.getText().toString();
    
08.07.2017 / 17:29