1

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

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()
    }
}
     }
vibhu
  • 369
  • 3
  • 10
  • Have you tried this: https://stackoverflow.com/questions/62671106/onactivityresult-method-is-deprecated-what-is-the-alternative This might solve your problem. – Douglas Cunha Jan 28 '22 at 11:55
  • yes, but not able to get desired result as i mention in the Question @DouglasCunha – vibhu Jan 28 '22 at 12:40

1 Answers1

1

what you need is registerForActivityResult() here is a sample project and you can read more about this new API

use-case : user by typing in input(Second Activity) and click button can recive input text in MainActivity(first activity):

MainActivity class:

    import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts

class MainActivity : AppCompatActivity() {
    lateinit var txt:TextView
    lateinit var btn:Button
    private val secondActivityWithResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult())
        { result ->
            if (result.resultCode == Activity.RESULT_OK){
                result.data?.getStringExtra("name")?.let { txt.text = it }
            }
        }
    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{
            secondActivityWithResult.launch(Intent(this,SecondActivity::class.java))
        }
    }
}

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 android.app.Activity
import android.content.Intent
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.return_btn)
        input = findViewById(R.id.my_input)

        btn.setOnClickListener{
            SharedValues.myString = input.text.toString()
            val intent = Intent()
            intent.putExtra("name","my love is NAHID MORADI")
            setResult(Activity.RESULT_OK,intent)
            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:hint="type here"

        android:inputType="textPersonName"
        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>
soheil ghanbari
  • 388
  • 1
  • 7
  • thank you @soheil but not able to get the desired result text is not change when i move from 2nd activity to main activity where as when i log the value of `sharedValue.myString` it is updating accordingly but not show on mainactivity – vibhu Jan 28 '22 at 12:45
  • as i said this is simple way and work just one time, for better usage you must optimize it, this is just an idea,but this link https://stackoverflow.com/questions/62671106/onactivityresult-method-is-deprecated-what-is-the-alternative is the best way that work in place of tartActivityForResult – soheil ghanbari Jan 28 '22 at 17:02
  • i edit by better solution registerForActivityResult() and whit complete code for you inform me if it is ok for you – soheil ghanbari Jan 28 '22 at 18:14
  • i'm able to to find out another solution for my problem that is why a bit late reply on this problem but this one also work... @soheil – vibhu Feb 06 '22 at 09:16
  • i suggest you always this way,be happy – soheil ghanbari Feb 06 '22 at 10:07