Android StartAcitivity for result Example

Using startActivity we can launch new Activity and pass the data to the newly launched activity and reverse of it that is getting data from launched activity we use startActivityForResult.

When using startActivity, your application won’t receive any notification when the newly launched .
If you use the startActivityForResult() method instead of startActivity  you can receive data from the newly launched subactivity .


Lets See san example :

Project Detail
Project Name StartActivityForResult
Package com.tutorialsbuzz.startactivityforresult
Min Sdk Version 15
Target Sdk Version 28
Compile Sdk Version 28
Theme Theme.AppCompat.Light.DarkActionBar

1. XML Layout 


file : screen_1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/launchActivity"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StartActivity For Result" />

    <TextView
        android:id="@+id/result"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

file : screen_2.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/inputVal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter your name"
        android:inputType="textPersonName">

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/finishActivity"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="finish Activity" />

</LinearLayout>

2. Activities


Onclick of Button call startActivityForResult() method it takes two parameter 1.intent 2.request code parameter.  request code is used to uniquely identify launched Activity.

file : MainActivity
package com.tutorialsbuzz.startactivityforresult;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Button mButton;
    private TextView mTextView;
    private static final int requestID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_1);

        mButton = findViewById(R.id.launchActivity);
        mTextView = findViewById(R.id.result);
        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, Next_Activity.class);
                startActivityForResult(i, requestID);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == requestID) {
            if (resultCode == Activity.RESULT_OK) {
                String ret_value = data.getStringExtra("key");
                mTextView.setText(ret_value);
            }
        }
    }

}


In the launched Activity .

  1. When your launched activity is ready to return, call setResult method before finish to return a result to the calling activity
  2. The setResult method takes two parameters the result code and the result itself,represented as intent.
  3. Once the launched activity get finish, the onActivityResult() method in the calling Activity will be called. Inside this method you can receive the data sent by launchedActivity.


file:Next_Activity.java
package com.tutorialsbuzz.startactivityforresult;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Next_Activity extends AppCompatActivity {

    private Button mButton;
    private EditText mEdittext;
    private String value = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_2);

        mButton = findViewById(R.id.finishActivity);
        mEdittext = findViewById(R.id.inputVal);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                value = mEdittext.getText().toString();
                Intent result = new Intent(Next_Activity.this, MainActivity.class);
                result.putExtra("key", value);
                setResult(RESULT_OK, result);
                finish();
            }
        });

    }
}

3. Android Manifest


Declare the Above Activities in Android Manifest .

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

    <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=".Next_Activity"/>
    </application>

</manifest>
Run



No comments:

Post a Comment