Skip to content

Getting a Result from an Activity| Android startActivityForResult Example Kotlin

Activity in the Android application development, you can do 2-way communication on starting a new Activity. A first Activity can get the result from another Activity. It can be done by call startActivityForResult() method instead of instead of startActivity() method.

get Result from an Activityc Android startActivityForResult

Build an app to get Result from an Activity using Android startActivityForResult method :

Think about one app which has 2 activity, one will be goto another one and 2nd activity will have a button to send some data back to Frist activity.

In this case, you need to override the onActivityResult method, it will that invoked when the second activity returns the result.

Method Signature

public void startActivityForResult (Intent intent, int requestCode)   public void startActivityForResult (Intent intent, int requestCode, Bundle options)  

See the below example for a better understanding of How to manage startActivityForResult on Android?

Step 1. Create a new project “Build Your First Android App in Kotlin

Step 2. Add following code in “activity_main.xml

In linearLayout there has textView and EditText.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:layout_margin="10dp"
        android:textSize="20sp"/>

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Second Activity"
        android:onClick="buttonClick1"
        android:layout_margin="10dp"/>

</LinearLayout>

Step 3. Create a new layout file and add the below code.

new layout file: src/layout/activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Type..."
        android:layout_margin="10dp"/>s

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go Back"
        android:onClick="buttonClick2"
        android:layout_margin="10dp"/>


</LinearLayout>

Step 4. Open the “MainActivity.kt” and add the following code

You must know about the Explicit intent and how to go to one activity to another activity.

package com.eyehunts.androidstartactivityforresult

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.app.Activity
import android.widget.TextView
import android.content.Intent
import android.view.View


class MainActivity : AppCompatActivity() {

    private val SECOND_ACTIVITY_REQUEST_CODE = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    // "Go to Second Activity" button click
    fun buttonClick1(view: View) {

        // Start the SecondActivity
        val intent = Intent(this, SecondActivity::class.java)
        startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE)
    }

    // This method is called when the second activity finishes
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // Check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {

                // Get String data from Intent
                val returnString = data!!.getStringExtra("keyName")

                // Set text view with string
                val textView = findViewById(R.id.textView) as TextView
                textView.text = returnString
            }
        }
    }
}

Step 5. Create a new Activity and add the below code.

In intent using setResult() method.

package com.eyehunts.androidstartactivityforresult

import android.app.Activity
import android.content.Intent
import android.widget.EditText
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity



/**
 * Created by Eyehunt Team on 2019-12-20.
 */

class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
    }

    // "Send text back" button click
    fun buttonClick2(view: View) {

        // Get the text from the EditText
        val editText = findViewById(R.id.editText) as EditText
        val stringToPassBack = editText.text.toString()

        // Put the String to pass back into an Intent and close this activity
        val intent = Intent()
        intent.putExtra("keyName", stringToPassBack)
        setResult(Activity.RESULT_OK, intent)
        finish()

    }


}

Step 7. Add “SecondActivity.kt” in manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.eyehunts.androidstartactivityforresult">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"/>
    </application>

</manifest>

Step 7. Now Run the application, in an emulator or on your Android device

Output screenshot Android startActivityForResult example:

Android start Activity for Result

Download source code of getting Result from an Activity in Kotlin

https://github.com/EyeHunts/AndroidSaveInstanceState

Q: What is difference between Android startActivityForResult() and startActivity()?

Answer:

startActivity(): start a another activity.

startActivityForResult(): starts another activity from your activity and it expects to get some data from newly started child activity

Q: How to Send data back to the Main Activity in Android?

Answer: The best (and easiest) way is to use an Intent:

See below java code:

MainActivity: Frist Activity call another activity

Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, SOME_UNIQUE_CODE);

Simply Override onActivityResult()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if (requestCode == REQUEST_CODE){
        if (resultCode == RESULT_OK){

            id = data.getExtras().getString("id");
        }
    }
}

MainActivity: Second Activity send data to first activity

intent = new Intent();
intent.putExtra("id", "Some Value Here to return");
setResult(RESULT_OK, intent);
finish();

Q: What are some examples of getting Results from an Activity?

Answer: Here are some app concept needed a use start Activity For Result:-

  • Camera App: the app can start a camera app and receive the captured photo as a result
  • Recharge App: user to select a contact and you’ll receive the contact details as a result.

Do comment if you have any doubts and suggestions on this tutorial. Write in a comment section if you have any use case suitable for this method.

Note: This example (Project) is developed in Android Studio 3.3.2. Tested on Android 9 ( Android-P), compile SDK version API 28: Android 9.0 (Pie)
MinSdkVersion=”25″
TargetSdkVersion=”28″
Coding in Kotlin

1 thought on “Getting a Result from an Activity| Android startActivityForResult Example Kotlin”

Leave a Reply

Your email address will not be published. Required fields are marked *