将字符串从一个活动发送到另一个活动时"Intent must not be null"



我是新来的Kotlin和我试图发送两个字符串从两个textview在一个活动到另一个使用意图。然而,当我运行函数load时,我得到了这个错误。

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pdm_2021_i_p1_project1, PID: 18672
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.pdm_2021_i_p1_project1/com.example.pdm_2021_i_p1_project1.PlayActivity}: java.lang.IllegalStateException: intent must not be null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.IllegalStateException: intent must not be null
at com.example.pdm_2021_i_p1_project1.PlayActivity.getWord(PlayActivity.kt:119)
at com.example.pdm_2021_i_p1_project1.PlayActivity.<init>(PlayActivity.kt:21)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 

这是我的代码从活动接收字符串

class PlayActivity : AppCompatActivity() {
//Variable Declarations
private val lives : Int = 4
private var fails : Int = 0
private var correctGuesses = mutableSetOf<Char>()
private var guesses = mutableSetOf<Char>()
private val word = getWord().toLowerCase(Locale.ROOT)
private val clue = getClue().toLowerCase(Locale.ROOT)
private val letters = word.toLowerCase(Locale.ROOT).toCharArray().toHashSet()
private val txtArray = arrayOfNulls<TextView>(word.length)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_play)
btnCheck.setOnClickListener{(checkWord())}
createTxtViews()
txvClue.text = clue.toUpperCase(Locale.ROOT)
txvLives.text = "❤❤❤❤"
}
private fun checkWord(){
val character = txtPlayAddLetter.text.toString().toLowerCase(Locale.ROOT)
if (txtPlayAddLetter.text.isNotEmpty()){
if (word.contains(txtPlayAddLetter.text.toString().toLowerCase(Locale.ROOT))) {
correctGuesses.add(character[0])
guesses.add(character[0])
txvGuessed.text = guesses.toString().toUpperCase(Locale.ROOT)
txvTest.text = letters.toString()
showLetters()
txtPlayAddLetter.text.clear()
checkGameState()
}
else
{
fails++
guesses.add(character[0])
txvGuessed.text = guesses.toString().toUpperCase(Locale.ROOT)
txtPlayAddLetter.text.clear()
val hearts = txvLives.text.dropLast(1)
txvLives.text = hearts
when (fails) {
1 -> {frame1.isVisible = false
frame2.isVisible = true}
2 -> {frame2.isVisible = false
frame3.isVisible = true}
3 -> {frame3.isVisible = false
frame4.isVisible = true}
4 -> {frame4.isVisible = false
frame5.isVisible = true}}
if (fails == lives)
{
showDefeat()
}
}
}
else
{
Toast.makeText(this@PlayActivity, "Please enter a letter :)", Toast.LENGTH_LONG).show()
}
}
private fun showDefeat(){
val intent = Intent(this, DefeatActivity::class.java)
finish()
startActivity(intent)
}
private fun showVictory(){
val intent = Intent(this, VictoryActivity::class.java)
finish()
startActivity(intent)
}
private fun createTxtViews(){
val lLayout = findViewById<View>(R.id.txtPlayGuessed) as LinearLayout
for (i in word.indices) {
txtArray[i] = TextView(this)
txtArray[i]?.id = i
txtArray[i]?.setTextColor(resources.getColor(R.color.white))
txtArray[i]?.hint = "  _  "
txtArray[i]?.setHintTextColor(resources.getColor(R.color.white))
txtArray[i]?.textSize = 25F
lLayout.addView(txtArray[i])
txtArray[i]?.isVisible = true
}
}
private fun showLetters(){
val str = txtPlayAddLetter.text.toString().toLowerCase(Locale.ROOT)
for (i in word.indices){
if (txtPlayAddLetter.text.single().toLowerCase() == word[i]){
txtArray[i]?.text = "  ".plus(str.toUpperCase(Locale.ROOT)).plus("  ")
}
}
}
private fun checkGameState(){
if (correctGuesses == letters){
showVictory()
finish()
}
}
fun getWord(): String{
val bundle=intent.extras
val setword= bundle?.get("setword")
return getString(R.string.setwordplay,setword)

}
fun getClue(): String{
val bundle = intent.extras
val setclue = bundle?.get("setclue")
return getString(R.string.setwordplay,setclue)
}}

这是我的代码从活动发送字符串

fun load(){
val intent = Intent(this, PlayActivity::class.java)
intent.putExtra("setword", editTextTypeAWord.text.toString())
intent.putExtra("setclue", editTextHint.text.toString())
startActivity(intent)
}

您正在尝试用Intent中的数据初始化val。在PlayActivity中,init{}块和属性初始化在onCreate()之前运行。

要解决这个问题,您可以尝试:

class PlayActivity : AppCompatActivity() {
companion object {
const val ARG_WORD = "word"
const val ARG_CLUE = "clue"
}
private lateinit var word: String
private lateinit var clue: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
word = intent.getStringExtra(ARG_WORD) ?: throw IllegalArgumentException("Word was not supplied")
clue = intent.getStringExtra(ARG_CLUE) ?: throw IllegalArgumentException("Clue was not supplied")
}
}

电话:

val intent = Intent(this, PlayActivity::class.java).apply { 
putExtra(PlayActivity.ARG_WORD, "giraffe")
putExtra(PlayActivity.ARG_CLUE, "long neck")
}
startActivity(intent)

另外,请记住重构依赖于wordclue的其他属性,以使用函数或getter,否则您将遇到UninitializedPropertyAccessException。使用getter所做的是每次调用属性时计算get()部分。因为你使用的是onCreate()之后的属性,你的lateinit属性应该已经从你收到的意图中初始化了!

class PlayActivity : AppCompatActivity() {
companion object {
const val ARG_WORD = "word"
const val ARG_CLUE = "clue"
}
private lateinit var word: String
private lateinit var clue: String
private val letters: HashSet<Char>
get() = word.toLowerCase(Locale.ROOT).toCharArray().toHashSet()
private val txtArray: Array<TextView?>
get() = arrayOfNulls<TextView>(word.length)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
word = intent.getStringExtra(ARG_WORD) ?: throw IllegalArgumentException("Word was not supplied")
clue = intent.getStringExtra(ARG_CLUE) ?: throw IllegalArgumentException("Clue was not supplied")
}
}

我强烈建议你阅读这个:https://kotlinlang.org/docs/properties.html

val intent = Intent(this, PlayActivity::class.java).apply {
putExtra("setword", message)
}
startActivity(intent)

试试这个

private fun showVictory(){
val intent = Intent(this, VictoryActivity::class.java)

startActivity(intent)
finish()
}

像这样使用

intent?.getStringExtra("setword")  ?: ""
intent?.getStringExtra("setclue")  ?: ""  

试试这个

fun getWord(): String{
val setword= intent.getStringExtra("setword")
return getString(R.string.setwordplay,setword)

}
fun getClue(): String{
val setclue = intent.getStringExtra("setclue")
return getString(R.string.setwordplay,setclue)
}}

最新更新