【发布时间】:2018-06-05 04:40:45
【问题描述】:
我正在使用 Android Studio 开发一个 Android 应用程序,但出现此错误:
尝试调用虚拟方法'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' 为空 对象引用
看来我的意图是空的,但我不明白为什么......
我的第一堂课:计时器
package com.example.work.lustucru
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.provider.AlarmClock.EXTRA_MESSAGE
const val EXTRA_MESSAGE = "com.example.lustucru.MESSAGE"
class Timer : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_timer)
}
/** Called when the user taps the Send button */
fun sendMessage(view: View) {
val editText = findViewById<EditText>(R.id.editText)
val message = editText.text.toString()
val intent = Intent(this, DisplayMessageActivity::class.java).apply {
this.putExtra(EXTRA_MESSAGE, message)
}
startActivity(intent)
}
}
我的第二堂课:DisplayMessageActivity
package com.example.work.lustucru
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class DisplayMessageActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_display_message)
// Get the Intent that started this activity and extract the string
val message = intent.getStringExtra(EXTRA_MESSAGE)
// Capture the layout's TextView and set the string as its text
val textView = findViewById<TextView>(R.id.textView).apply {
text = message
}
}
}
【问题讨论】:
-
我相信您可能使用了错误的
EXTRA_MESSAGE值。 -
似乎 EXTRA_MESSAGE 值未在 DisplayMessageActivity 中导入
-
我试图检查
if(intent !=null),但我没有进入if,所以似乎没有定义意图......:/