Android错误:尝试在空对象引用上调用虚方法'java.lang.String android.content.Intent.getStringExtra(java.lang.String)'

时间:2018-06-03 21:33:57

标签: java android kotlin

我正在使用Android Studio安装Android应用,但是我收到了这个错误:

  

尝试调用虚方法'java.lang.String   android.content.Intent.getStringExtra(java.lang.String)'为null   对象参考

所以似乎我的意图是空的,但我不明白为什么......

我的第一堂课:计时器

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
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您需要进行此导入      import android.provider.AlarmClock.EXTRA_MESSAGE 在您的DisplayMessageActivity类中,以便具有EXTRA_MESSAGE消息值。您的EXTRA_MESSAGE变量目前不存在。