I have an edit text from where I am taking the text and sending it to MainActivity using putExtra()
but when the getStringExtra()
is returning null.
SecondActivity:-
val intent = Intent(this, MainActivity::class.java)
if(editWordView.text.isNotEmpty()){
val word = editWordView.text.toString()
intent.putExtra("Word", word)
startActivity(intent)
}
In first log it is showing null and last line is not executing as the word is null
MainActivity:-
val intent = Intent()
val word = intent.getStringExtra("Word")
Log.d(TAG, "MainActivity: $word")
word?.let {
viewModel.insert(Word(word))
Log.d(TAG, "onCreate: Inserted $word")
}
CodePudding user response:
Delete:
val intent = Intent()
You are creating a new, empty Intent
. That will not contain any extras. Instead, you need to get the Intent
from the activity:
- via
getIntent()
for theIntent
used to create the activity - in
onNewIntent()
for anyIntent
used to bring an already-running instance of this activity back to the foreground
CodePudding user response:
To get value in the Second activity you can also try this, it works perfect for me!
val word = intent.extras?.getString("Word")