I'm working on a school project that requires me to create an app in Android Studio with Kotlin that uses RecyclerView to create a list with clickable elements. Most of these labels, when clicked, will display their class' respective variables in a separate activity. But two of them, the add and delete labels, allow the user to add their own items or delete them while updating the RecyclerView dynamically. I've been able to get everything else to work EXCEPT the add/delete labels because I can't get the RecyclerView to update. Is there any way to start a second activity, get the inputs from the user, and pass those variables back to the first activity?
-
show your code. – Mahi Oct 08 '22 at 10:24
1 Answers
I sincerely hope you can provide something to show everybody what you have done so far, but to help you out with
Is there any way to start a second activity, get the inputs from the user, and pass those variables back to the first activity?
I would assume you already know how to pass data from one activity to another using Bundle
. That being said, this would be a good start for you
ActivityA
class ActivityA : AppCompatActivity() {
private lateinit var binding: ActivityABinding
private val startForResult = registerForActivityResult(StartActivityForResult()) { result: ActivityResult ->
result.data?.let {
it.extras?.let {
Log.e("ResultFromActivityB", "${it.getString("FromActivityB")}")
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityABinding.inflate(layoutInflater)
setContentView(binding.root)
binding.toActivityA.setOnClickListener {
startForResult.launch(Intent(this@ActivityA, ActivityB::class.java))
}
}
ActivityB
class ActivityB : AppCompatActivity() {
private lateinit var binding: ActivityBBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.backToA.setOnClickListener {
val resultIntent = Intent()
resultIntent.putExtra("FromActivityB", "Activity B Result.")
setResult(1, resultIntent)
finish()
}
}
}
ActivityA
will launch ActivityB
, pressing the button from ActivityB
will finish it and returns a result
to ActivityA
This is just a barebone working example on how to implement ResultApi that fits your usecase, however, there are alot of things I left that you should probably further research on, like creating your own ActivityContract
.
You can visit these other S.O posts
How to replace startActivityForResult with Activity Result APIs?
Android: startActivityForResult & setResult for a view class and an activity class

- 5,512
- 4
- 10
- 36