从意图中获取空值

时间:2019-03-23 12:18:59

标签: android android-intent kotlin

我试图将两个字符串从AddNote传递给MainActivity。但是它一直在变为空。 无法启动活动(MainActivity)

java.lang.IllegalStateException: callingIntent.getStringExtra("intentTitle") must not be null  
class MainActivity : AppCompatActivity() {

    private val notes = arrayListOf<Note>()

    private val db by lazy {
        Room.databaseBuilder(this
            ,NoteDatabase::class.java
            ,"NoteDatabase.db")
        .allowMainThreadQueries()
            .build() }

    lateinit var adapter: adapter

    lateinit var title: String
    lateinit var content: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        notes.addAll(db.dao().getNotes())

        AddNote.setOnClickListener {
            val i = Intent(this@MainActivity,AddNote::class.java)
            startActivity(i)
        }

        // startActivity(Intent(this, AddNote::class.java))

        val callingIntent = intent

        title = callingIntent.getStringExtra("intentTitle")
        content = callingIntent.getStringExtra("intentContent")

        val note = Note(title,content)

        val id = db.dao().insert(note)
        note.id = id.toInt()

        notes.add(note)

        adapter = adapter(notes, db)
        rootView.layoutManager = LinearLayoutManager(this)
        rootView.adapter = adapter
    }

    override fun onResume() {
        super.onResume()
        notes.clear()
        notes.addAll(db.dao().getNotes())
        adapter.notifyDataSetChanged()
    }
}


class AddNote : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.add_note)

        var intentTitle = "Title"
        var intentContent = "Content"

        saveNote.setOnClickListener {

            intentTitle = addTitle.text.toString()
            intentContent = addContent.text.toString()

        }

        val i = Intent()

            i.putExtra("title",intentTitle)
            i.putExtra("content",intentContent)

            startActivity(i)
    }
}

2 个答案:

答案 0 :(得分:0)

您必须将以MainActivity开头的代码放在saveNote.setOnClickListener中:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.add_note)

    var intentTitle = "Title"
    var intentContent = "Content"

    saveNote.setOnClickListener {
        intentTitle = addTitle.text.toString()
        intentContent = addContent.text.toString()
        val i = Intent(this, MainActivity::class.java)
        i.putExtra("title",intentTitle)
        i.putExtra("content",intentContent)
        startActivity(i)
    }
}

您的代码的工作方式是在加载AddNote活动后立即启动MainActivity,因此我不确定您要做什么。

答案 1 :(得分:0)

您必须像这样开始活动...

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", value)
startActivity(intent)