将字符串从另一个活动推送到数组

时间:2019-01-11 09:40:37

标签: android arrays kotlin

my aplication

我有2个活动,第一个是CategoryActivity,第二个是QuestionActivity。 在CategoryActivity中,我有一个列出类别的recyclerview,在Category Activity中,我有一个数组。当我单击eksterior时,它将转到questionActivity,当我单击提交时,它将返回CategoryActivity并将数据发送到CategotyActivity。发送的数据已输入到数组中,因此数组将如下所示:array [] = {“ 1”};然后我在内部的recyclerview中单击第二个项目,然后再次转到QuestionActivity,当我单击Submit时,它将数据发送到CategoryActivity并将其添加到先前的数组中,因此该数组将如下所示:array [] = {“ 1”,“ 1”};依此类推,直到recyclerview上的项目用完为止。我已经尝试过了:

QuestionActivity.kt

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

    button_save.setOnClickListener(){
        val intent = Intent(this@ResultActivity, KategoriActivity::class.java)
        intent.putExtra(KategoriActivity.Companion.ARRAY, "1")
        startActivity(intent)
    }
}

CategoryActivity.kt

var list = arrayOf(intent.getStringExtra(ARRAY))
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_category)
    Toast.makeText(this@KategoriActivity, ""+ list, Toast.LENGTH_SHORT).show()


}
companion object {
    val ARRAY = "array"

}

override fun onBackPressed() {
    Toast.makeText(this@KategoriActivity, ""+ list, Toast.LENGTH_SHORT).show()
    if (list.size == kategoriDatas!!.size){
        onBackPressed()
    } else {
        val builder = AlertDialog.Builder(this)
        builder.setMessage("You Must Finish All The Category")

        // add a button
        builder.setPositiveButton("OK", null)

        // create and show the alert dialog
        val dialog = builder.create()
        dialog.show()
    }
    }

问题是当我打开类别活动时,该应用程序停止了,并且日志显示为Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference

数据无法推送到数组,请帮助我

1 个答案:

答案 0 :(得分:0)

仅在创建活动后才能获得意图。为了确保它是最好的,如果您将要从Intents中获取额外内容的代码放入onCreate中。

赞:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_category)
    Toast.makeText(this@KategoriActivity, ""+ list, Toast.LENGTH_SHORT).show()
    var list = arrayOf(intent.getStringExtra(ARRAY))
}

如果您想拥有一个包含信息的Application类:

class MyApplication : Application(){
var list = emptyArray<String>()

  override fun onCreate() {
    super.onCreate()
  }
}

要在您的活动中使用它:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_category)
    Toast.makeText(this@KategoriActivity, ""+ list, Toast.LENGTH_SHORT).show()
    var list = (application as MyApplication).list
   // you can than use it to update or retrieve values from it
}