Home > database >  Android with Kotlin - Sending data back to MainActivity
Android with Kotlin - Sending data back to MainActivity

Time:04-12

I have two activities. I want to receive a value from MainActivity, change the value from SecondActivity, and send it back to editText of MainActivity.

However, the editText of MainActivity does not change even if I move back from SecondActivity.

Could you tell me which part I misunderstood?

MainActivity.kt code

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import com.example.homework07.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val result = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            it.resultCode
            val ret_num = it.data?.getIntExtra("result", 0) ?:0

            Snackbar.make(binding.root, "result code: ${it.resultCode}, result number: ${ret_num}", Snackbar.LENGTH_SHORT).show()
        }

        binding.button.setOnClickListener {
            val intent = Intent(this, SecondActivity::class.java)
            intent.putExtra("num", Integer.parseInt(binding.editText.text.toString()))
            result.launch(intent)
        }
    }
}

activity_main.xml code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@ id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="Enter number only"
        android:inputType="number"
        android:minHeight="48dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@ id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="START SECOND ACTIVITY"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>

SecondActivity.kt code

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.example.homework07.databinding.ActivitySecondBinding

class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivitySecondBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val viewModel = ViewModelProvider(this)[MyViewModel::class.java]
        viewModel.myLiveData.observe(this) {
            binding.textView.text = "$it"
        }

        var num2 = intent?.getIntExtra("num", 0) ?:0
        binding.textView.text = "$num2"

        binding.buttonInc.setOnClickListener {
            num2 = viewModel.myLiveData.value ?:0
            viewModel.myLiveData.value = Integer.parseInt(binding.textView.text.toString())   1
        }

        binding.buttonDec.setOnClickListener {
            num2 = viewModel.myLiveData.value ?:0
            viewModel.myLiveData.value = Integer.parseInt(binding.textView.text.toString()) - 1
        }

        setResult(0, Intent().putExtra("result", num2))
    }
}

activity_second.xml code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">

    <TextView
        android:id="@ id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="32dp"
        android:text="TextView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@ id/buttonInc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="INCREASE"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@ id/textView"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@ id/buttonDec"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="DECREASE"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@ id/textView"
        app:layout_constraintTop_toBottomOf="@ id/buttonInc" />
</androidx.constraintlayout.widget.ConstraintLayout>

MyViewModel.kt code

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class MyViewModel : ViewModel() {
    val myLiveData : MutableLiveData<Int> = MutableLiveData()
}

Thank you.

CodePudding user response:

You made a mistake:

setResult(0, Intent().putExtra("result", num2))

replace 0 (it cancel result) to Activity.RESULT_OK.

CodePudding user response:

This line has a mistake (resultCode) parameter:

setResult(0, Intent().putExtra("result", num2))

It's better if you make a constant for resultCode or do something like this in your SecondActivity.kt.

setResult(200, Intent().putExtra("result", num2))

And in MainActivity.kt add this is "registerActivityForResult":

if(it.resultCode == 200){ 
   //Rest of the code here
}

Or you can also follow Below answer

  • Related