I'm new at Kotlin, and I'm doing a simple app where the user writes something on EditText
, presses a button then the app proceeds to show that text on SecondActivity
, on that SecondActivity
the user can do exactly the same thing, but on the FirstActivity
(the one who shows up on the user starts the app) there are on EditText
with "Welcome" text for default that shows empty when the application starts, this started to happen when I implement the text to be substituted by what the user writes on the SecondActivity
Here's the code for the FirtActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val result = findViewById<TextView>(R.id.nomeUser)
val nameEntered = findViewById<EditText>(R.id.nameEntered)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener{
val name = nameEntered.text.toString()
val intent = Intent(this@MainActivity, NomeEscrito::class.java)
intent.putExtra("Name", name)
startActivity(intent)
}
val intent = intent
val name = intent.getStringExtra("Name")
result.text = name
}
}
And here's the code for the SecondActivity
class NomeEscrito : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nome_escrito)
val intent = intent
val name = intent.getStringExtra("Name")
val result = findViewById<TextView>(R.id.result)
result.text = name
val wordEntered = findViewById<EditText>(R.id.textPhrase)
val button2 = findViewById<Button>(R.id.button2)
button2.setOnClickListener{
val name2 = wordEntered.text.toString()
val intent2 = Intent(this@NomeEscrito, MainActivity::class.java)
intent2.putExtra("Name", name2)
startActivity(intent2)
}
}
}
CodePudding user response:
The problem is in the following line of your FirstActivity
:
val name = intent.getStringExtra("Name")
When you open up the app for the first time, there is no data in the intent
. As a result, it returns an empty string.
You can do the a check for empty string before setting your EditText
text to avoid this situation:
if (!name.isNullOrBlank()) {
result.text = name
}
CodePudding user response:
Choose different keys in getStringExtra in both intent data passing