In this lesson:

- getting result from the started activity

Sometimes we need to start an activity, make some action and return a results to starter activity. For example: while sending sms. When you push "add contact" button, android will show you an activity with your contact list, after adding the contact, you need, you’ll be returned to sms-creation activity. As you see, your contact list activity returns a contact information as a result.

You can read about it here and here.

Let’s have some practise and create an app with two activities. We will start second activity from the first, enter data and return it to the calling activity. We will request a username this way.

 

Let’s create a new project: 

Project name: P0291_SimpleActivityResult
Build Target: Android 2.3.3
Application name: SimpleActivityResult
Package name: ru.startandroid.develop.p0291simpleactivityresult
Create Activity: MainActivity

 

Open main.xml and code this screen:  

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/btnName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="20dp"
        android:text="Input name">
    </Button>
    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Your name is ">
    </TextView>
</LinearLayout>

Here is TextView that will show username and a Button for starting the second activity.

 

Let’s code MainActivity.java:

package ru.startandroid.develop.p0291simpleactivityresult;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
  
  TextView tvName;
  Button btnName;
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tvName = (TextView) findViewById(R.id.tvName);
        btnName = (Button) findViewById(R.id.btnName);
        btnName.setOnClickListener(this);
        
    }

  @Override
  public void onClick(View v) {
    Intent intent = new Intent(this, NameActivity.class);
    startActivityForResult(intent, 1);
  }
  
  
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data == null) {return;}
    String name = data.getStringExtra("name");
    tvName.setText("Your name is " + name);
  }
}

Here we define views and set an onClickListener. Then we create a new Intent with second activity class within the onClick method (don’t pay attention on warning, we will create this activity later). We use startActivityForResult to start second activity and MainActivity will start being "parent" for NameActivity (in difference from simple startActivity). After destroying NameActivity, MainActivity onActivityResult method is called, noticing us this way that the activity, which we started with startActivityForResult is now destroyed.

We pass Intent and requestCode as parameters to startActivityForResult. requestCode is necessary for authentification. We will define it in this lesson, but won’t use. The next lesson we will find out it’s usage in detail.

Here are parameters for onActivityResult:
requestCode - is the same, as in startActivityForResult. We can identify returning result activity with it.
resultCode - is return code, it indicates whether the call passed successfully or not.
data - is intent with data.

We won’t use requestCode and resultCode, we will find out it’s usage the next lesson. We will get name variable from data and set its value to TextView.

So, if we get name variable from data, something must put it there. NameActivity will deal with it.

Let’s code name.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">
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp">
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name">
        </TextView>
        <EditText
            android:id="@+id/etName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1">
            <requestFocus>
            </requestFocus>
        </EditText>
    </LinearLayout>
    <Button
        android:id="@+id/btnOK"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="OK">
    </Button>
</LinearLayout>

We will enter the name in EditText and press OK button.

 

Now, let’s create NameActivity and add it to manifest:

package ru.startandroid.develop.p0291simpleactivityresult;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class NameActivity extends Activity implements OnClickListener {
  
  EditText etName;
  Button btnOK;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.name);
    
    etName = (EditText) findViewById(R.id.etName);
    btnOK = (Button) findViewById(R.id.btnOK);
    btnOK.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    Intent intent = new Intent();
    intent.putExtra("name", etName.getText().toString());
    setResult(RESULT_OK, intent);
    finish();
  }
}

Define views and set onClickListener. We create a new Intent within onClick and stuff it with data from EditText. Note that we don’t give any pass to this intent (we don’t define action or class). So the pass is undefinite now. Not so, exactly. setResult method knows how to pass this intent - to the "parent" activity, where startActivityForResult method was called. We also pass RESULT_OK constant with setResult, that means that the call was successfully complete. This constant will set up resultCode of onActivityResult in MainActivity.java. Next lesson we will speak about it in detail. Then we call finish() for NameActivity and the result will pass to MainActivity.

 

Now let’s save and launch our project.

First we see MainActivity layout:

Now press the button to pass to NameActivity, where we will enter the username

 

Enter the username and press "Ok" button

 

Now we are back to the MainActivity layout

 

So, let’s sum up! We created new Intent in MainActivity with explicit referring to NameActivity class and launched it with the startActivityForResult method. NameActivity appeared, so we entered the username and clicked the button, after that Intent was created with the username variable inserted. setResult method knows, that the intent must be returned to parent Activity, which called startActivityForResult method, i.e. MainActivity. MainActivity method onActivityResult is responsible for catching results from launched activities. Within it we unpacked Intent and set the data we got to TextView.

Now we only must understand this pattern:

 

 

The next lesson we will make more extended and demonstrative example of this technology usage.

 

The next lesson:

- we will find out usage of requestCode and resultCode in onActivityResult

 


Присоединяйтесь к нам в Telegram:

- в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

- в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Compose, Kotlin, RxJava, Dagger, Тестирование, Performance 

- ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня




Language