【问题标题】:Android Error : Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object referenceAndroid 错误:尝试在空对象引用上调用虚拟方法“java.lang.String android.content.Intent.getStringExtra(java.lang.String)”
【发布时间】: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,所以似乎没有定义意图......:/

标签: java android kotlin


【解决方案1】:

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

【讨论】:

  • 我试图检查if(intent !=null),但我没有进入 if,所以似乎没有定义意图...:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 2017-09-01
  • 1970-01-01
相关资源
最近更新 更多