女士们先生们。我目前正在开发一个简单的应用程序,它可以计算所需的卡路里量,以增加,减少或保持体重。该应用程序由七个活动组成。其中六个专门用于应用指定的参数(例如年龄、身高等)。这些参数保存在文件“Variables.kt”中。第七个活动必须显示所有已执行的参数,并显示完成所需计划所需的卡路里量。
**我遇到的问题:**原来每一个参数都得到了第六个活动中实现的数据。
下面是示例代码:
FirstActivity.kt:
// Variables
val intentGoToSecondActivity = Intent(this@FirstActivity, SecondActivity::class.java)
// Main part of the code
buttonFirstActivity.setOnClickListener {
intentGoToSecondActivity.putExtra(Variables.firstMessage, "First message")
startActivity(intentGoToSecondActivity)
}
SecondActivity.kt:
// Variables
val getData = intent.extras
val intentGoToThirdActivity = Intent(this@SecondActivity, ThirdActivity::class.java)
// Main part of the code
buttonSecondActivity.setOnClickListener {
intentGoToThirdActivity.putExtra(Variables.firstMessage, intent.getStringExtra(Variables.firstMessage))
intentGoToThirdActivity.putExtra(Variables.secondMessage, "Second message")
startActivity(intentGoToThirdActivity)
}
ThirdActivity.kt(假设它是显示已实现数据的第七个Activity
// Variables
val getData = intent.extras
// Main part of the code
buttonThirdActivity.setOnClickListener {
// Getting data from Variables.kt
val firstMessage = getData?.getString(Variables.firstMessage)
val secondMessage = getData?.getString(Variables.secondMessage)
// Displaying gotten data
displayData.text = firstMessage + "\n" + secondMessage
}
当我单击ButtonThirdActivity.kt时,它显示“SecondmessageSecondmessage”,而不是“FirstmessageSecondmessage”。我提供的代码有什么问题?
1条答案
按热度按时间nhaq1z211#
要解决第七个活动中参数无法正确获取已实现数据的问题,可以考虑使用以下方法:
1.您可以使用Intent extra或启动新Activity时作为参数在Activity之间传递数据,而不是将参数保存在单独的文件(如“Variables.kt”)中。
1.在用户输入参数(年龄、身高等)的每个Activity中,检索输入数据并在启动下一个Activity时将其传递给它。例如,当从第五个Activity移动到第六个Activity时,将数据从第五个Activity传递到第六个Activity。
1.在第七个活动中,从前面的活动中检索传递的数据,并根据所需的计划计算所需的卡路里量。
以下是如何实现此解决方案的示例:
在第五项活动中:
在第六项活动中:
第七项活动:
通过使用Intent extra在Activity之间传递数据,您可以确保在第七个Activity中提供正确的数据来计算所需的卡路里量。