[英]Android Error : Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
I'm working on a Android app with Android Studio, but I'm getting this error : 我正在使用Android Studio开发一个Android应用,但出现此错误:
Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference 尝试在空对象引用上调用虚拟方法'java.lang.String android.content.Intent.getStringExtra(java.lang.String)'
So it's seem that my intent is null, but I'm not getting why... 所以看来我的意图是空的,但我不明白为什么...
My first class : Timer 我的第一堂课:计时器
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)
}
}
My second class : DisplayMessageActivity 我的第二堂课: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
}
}
}
i think you need to make this import import android.provider.AlarmClock.EXTRA_MESSAGE in your DisplayMessageActivity class so as to have the EXTRA_MESSAGE message value. 我认为您需要在DisplayMessageActivity类中将此导入导入android.provider.AlarmClock.EXTRA_MESSAGE,以便具有EXTRA_MESSAGE消息值。 your EXTRA_MESSAGE variable currently does not exists. 您的EXTRA_MESSAGE变量当前不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.