skip to Main Content

I’m just new to Kotlin and Android Studio.

I’m trying to access the text of the input (editText) and do some processing before showing it, but I’m not able to do it.

I’m trying three different "variations", but any of them work.

.xml

<EditText
        android:id="@+id/placa"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/placa"
        android:autofillHints=""
        android:layout_gravity="center_horizontal"
        android:inputType="text"/>

Kotlin:

// Objects
val button: Button = findViewById(R.id.consultar)
val editTextPlaca: EditText = findViewById(R.id.placa)

// Strings
val placa = editTextPlaca.text
val placa2 = editTextPlaca.text.toString()
val placa3 = editTextPlaca.getText().toString()

// Process String
val mensaje = "The plate is " + placa + placa2 + placa3

button.setOnClickListener {
    Toast.makeText(this, mensaje, Toast.LENGTH_SHORT).show()
}

The output I get is just: "The plate is "

Thanks for your help.

2

Answers


  1. You’re assigning the value to the string variables placa, placa2, and placa3 before the button clicks even if the user has not entered any text in the EditText.

    Read the value from EditText when the button is clicked.

    // Objects
    val button: Button = findViewById(R.id.consultar)
    val editTextPlaca: EditText = findViewById(R.id.placa)
    
    button.setOnClickListener {
        val mensaje = "The plate is ${editTextPlaca.text.toString()}"
        Toast.makeText(this, mensaje, Toast.LENGTH_SHORT).show()
    }
    

    Note: I have used the $ operator to concatenate the text.

    Login or Signup to reply.
  2. You have this output because you extracted the text at the very beginning, not at the moment of the button click.

    By the way, Kotlin has a handy String interpolation feature, so you don’t have to concatenate it with ‘+’. You can do something like this:

    button.setOnClickListener {
        val mensaje = "The plate is ${editTextPlaca.text}"
        //further logic
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search