gpt4 book ai didi

android - 从另一个 Activity 将字符串推送到数组

转载 作者:行者123 更新时间:2023-11-30 05:08:23 25 4
gpt4 key购买 nike

my aplication

我有 2 个 Activity ,第一个是 CategoryActivity,第二个是 QuestionActivity。在 CategoryActivity 中,我有一个列出类别的 recyclerview,在 Category Activity 中,我有一个数组。当我单击 eksterior 时,它将转到 questionActivity,当我单击提交时,它将返回到 CategoryActivity 并将数据发送到 CategotyActivity。发送的数据被输入到数组中,所以数组将是这样的: array[] = {“1”};然后我点击recyclerview中的第二个item是interior,然后它会再次进入QuestionActivity,当我点击提交时,它会将数据发送到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()
}
}

问题是当我打开类别 Activity 时,应用程序停止了,并且日志显示 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent .getStringExtra(java.lang.String)' 在空对象引用上

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

最佳答案

您只能在 Activity 创建后获取 Intent 。为了确保这一点,最好将将从 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()
}
}

在您的 Activity 中使用它:

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
}

关于android - 从另一个 Activity 将字符串推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54143852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com