Home > Back-end >  take data from child activity to main activity in kotlin
take data from child activity to main activity in kotlin

Time:01-28

Hi all I'm new to android development(I'm using Kotlin) and startActivityForResult is deprecated trying to make one simple app To make it simple :

I have a main activity with two button first activity and second activity.

I have a "child" activity with a text fields and a finish button.

When I click the main activity button, the child activity opens (it works data can also be access which i pass from main activity). Then I put some text to the text fields and when I click the finish button I want the data from the text fields to be transferred to the main activity, and I can't get this working. followed medium, yt and stackoverflow not able to make it work may be its overwhelming

my main activity code

   package com.example.data

 import android.app.Activity
import android.app.Instrumentation
import android.content.Intent
    import androidx.appcompat.app.AppCompatActivity
  import android.os.Bundle
 import android.preference.PreferenceManager
 import android.widget.Button
  import android.widget.EditText
  import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
 import androidx.activity.result.contract.ActivityResultContracts

  class MainActivity : AppCompatActivity() {
companion object{
  private const val FIRST_ACTIVITY_RESULT = 1
}
lateinit var activityResultLauncher: ActivityResultLauncher<Intent>

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val firstbtn = findViewById<Button>(R.id.first_activity_btn)
    val first_text = findViewById<TextView>(R.id.first_activity_text)
    val secondbtn = findViewById<Button>(R.id.second_activity_btn)
    val edit = findViewById<EditText>(R.id.edit_name)


     firstbtn.setOnClickListener{
        var intent = Intent(this,first_activity::class.java)
      intent.putExtra("data_name",edit.text.toString())
        activityResultLauncher.launch(intent)

        finish()
    }

    secondbtn.setOnClickListener{
        var intent = Intent(this,second_activity::class.java)
        startActivity(intent)
        finish()
    }

    activityResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()){ result:ActivityResult?->
        if (result!!.resultCode == Activity.RESULT_OK){
            if(result.data!!.extras!!.getString("data_transfer").toString() == "yes"){

                Toast.makeText(applicationContext, "user send reply", Toast.LENGTH_SHORT).show()
            }else{
                Toast.makeText(applicationContext, "sorry user did not send reply", Toast.LENGTH_SHORT).show()
            }
        }
    }

  }
       }

first activity code

   package com.example.data

  import android.app.Activity
  import android.content.Intent
 import androidx.appcompat.app.AppCompatActivity
 import android.os.Bundle
 import android.widget.Button
  import android.widget.EditText
  import android.widget.TextView

    class first_activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_first)
    val finish = findViewById<Button>(R.id.finish_btn)
    val textData = findViewById<TextView>(R.id.tv_first_activity)
    val edit = findViewById<EditText>(R.id.edit_text_first_activity)

    textData.text = intent.extras!!.getString("data_name")

    finish.setOnClickListener{
  //            val intent = Intent(this,MainActivity::class.java)
    //            intent.putExtra("success","success message woohooo!!!")
      //            startActivity(intent)
        val intent = Intent()
   //            val intent = Intent(this,MainActivity::class.java)
        intent.putExtra("data_transfer",edit.text.toString())
        setResult(Activity.RESULT_OK,intent)
    //            startActivity(intent)
        finish()
    }
}
     }

CodePudding user response:

Try to change the activityResultLauncher declaration like this (initialize it before the onCreate method):

private val activityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    if (result.resultCode == Activity.RESULT_OK) {
        val response = result.data?.getStringExtra("data_transfer") ?: ""
        if (response == "yes") {
            Toast.makeText(applicationContext, "user send reply", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(applicationContext, "sorry user did not send reply", Toast.LENGTH_SHORT).show()
        }
    }
}

Also, remove the finish() statement from the setOnClickListener of the firstbtn:

firstbtn.setOnClickListener{
    var intent = Intent(this,first_activity::class.java)
    intent.putExtra("data_name",edit.text.toString())
    activityResultLauncher.launch(intent)
}

CodePudding user response:

you need to use Object classes this.

fields inside this class treat as static field in Java and they are availabe in whole of app, after finishing seconactivity in onRestart() method first activity you can get value which added to our Object (static)

make a object class and name it SharedValue and put below code inside that:

object SharedValues {
var myString = ""
 }

MainActivity class:

    import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    lateinit var txt:TextView
    lateinit var btn:Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn = findViewById(R.id.next_activity)
        txt = findViewById(R.id.returned_text)

        btn.setOnClickListener{
            var intent = Intent(this,SecondActivity::class.java)
            startActivity(intent)
        }


    }

    override fun onRestart() {
        super.onRestart()
        if(SharedValues.myString !=""){
            txt.text =SharedValues.myString
        }

    }
}

activity_main.xml :

    <?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">

    <Button
        android:id="@ id/next_activity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@ id/returned_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="your string appear here"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

SecondActivity class :

    import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText

class SecondActivity : AppCompatActivity() {
    lateinit var input:EditText
    lateinit var btn:Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
        btn = findViewById(R.id.returned_text)
        input = findViewById(R.id.my_input)

        btn.setOnClickListener{
            SharedValues.myString = input.text.toString()
            finish()
        }
    }
}

activity_second.xml:

    <?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">

    <EditText
        android:id="@ id/my_input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="88dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@ id/return_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="76dp"
        android:text="Return To FirstActivity"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/my_input" />
</androidx.constraintlayout.widget.ConstraintLayout>
  •  Tags:  
  • Related