Unable to send string from one activity to another (third activity) in Android Studio using Kotlin

354 Views Asked by At

So I have three activities for my app. I am taking the username from the user(on Main Screen) and I want to show it to the last screen (Result Screen). I have tried using string constants and then sending the string value using Intent from one activity to the second and to the third one. But I am not able to see the name on the Result Screen. What is that I am doing wrong ?

I am following all the rules and the app is working fine without errors but the username is not been shown to the screen.

In Constants.kt

 const val USER_NAME: String = "user_name"    

In MainActivity.kt

val nameEditText = findViewById<TextView>(R.id.name_edit_text)  
val name = nameEditText.text.toString()  
val Intent = Intent(this, QuizQuestionActivity::class.java)  
intent.putExtra(Constants.USER_NAME, name)  
startActivity(intent)
       

In QuizQuestionActivity.kt

private var mUsername: String? = null 
mUsername = intent.getStringExtra(CONSTANTS.USER_NAME) 
val intent = Intent(this, ResultActivity::class.java)  
intent.putExtra(Constants.USER_NAME, mUsername)  
startActivity(intent)

In ResultActivity.kt

val username = intent.getStringExtra(Constants.USER_NAME)  
tv_name.text = username

This is the whole code I am trying to execute. Anybody please help!!

1

There are 1 best solutions below

1
yogesh Dande On

I have two Observations in your code snippet

1)Do you have two Constant files?

  1. Constant.kt
  2. CONSTANT.kt

As in your QuizQuestionActivity, there is a line

mUsername = intent.getStringExtra(CONSTANTS.USER_NAME)

No matter the file that you refer to, the USER_NAME field string values should be the same.

2)Another thing in MainActivity

val Intent = Intent(this, QuizQuestionActivity::class.java)
intent.putExtra(Constants.USER_NAME, name)  
startActivity(intent)

Here variable that you use is "Intent"

val Intent = Intent(this, QuizQuestionActivity::class.java)

and you pass "intent" for starting activity

intent.putExtra(Constants.USER_NAME, name)  
startActivity(intent)

Try this

In MainActivity:

val nameEditText = findViewById<TextInputEditText>(R.id.name_edit_text)
val name = nameEditText.text.toString()
val intent = Intent(this, QuizQuestionActivity::class.java)
intent.putExtra(Constants.USER_NAME, name)
startActivity(intent)

In QuizQuestionActivity:-

var mUsername: String? = null
mUsername = intent.getStringExtra(Constants.USER_NAME)
val intent = Intent(this, ResultActivity::class.java)
intent.putExtra(Constants.USER_NAME, mUsername)
startActivity(intent)

In ResultActivity:-

val username = intent.getStringExtra(Constants.USER_NAME)
tv_name.text = username