Lập trình Android – Truyền dữ liệu giữa Activity

Cách Truyền Dữ Liệu Qua Lại Giữa Các Activity

Chúng ta chỉ có duy nhất một cách để truyền dữ liệu qua lại giữa các Activity. Đó là cách “nhét” dữ liệu vào Intent và nhờ thành phần này chuyển giúp. Hệ thống sẽ đảm bảo dữ liệu được gửi qua “nguyên vẹn” và kịp thời ở Activity mới.

Ồ, vậy Intent ngoài việc kích hoạt các thành phần của Android, trong đó có Activity như bạn đã biết, nay lại có công năng của “người vận chuyển” nữa.

1.Truyền dữ liệu đến thành phần đích

Dữ liệu được “nhét” vào trong Intent và được lấy ra khỏi Intent theo các cặp dữ liệu dạng key/value. Key ở đây là một chuỗi, giúp định danh cho dữ liệu value. Nếu bạn để vào trong Intentcặp key/value nào, thì bạn phải lấy ra bởi cặp key/value đó, phải đảm bảo khai báo đúng key và lấy ra đúng kiểu dữ liệu của value khi để vào. Điều này tương tự như khi bạn di chuyển đi chơi xa, thì khi đóng gói hành lý của bạn, nhân viên tiếp nhận hành lý phải dán nhãn tên của bạn hay ID của bạn lên hành lý, để đảm bảo bạn lấy đúng hành lý (chính là value) khi đến nơi dựa vào nhãn tên hay ID đó (chính là key).

Tuy có một cách thôi, nhưng bạn có thể sử dụng một trong hai hình thức sau. Một là sử dụng Extra, hoặc sử dụng Bundle. Sự khác nhau giữa hai cách này theo mình là không quan trọng, bạn nên biết cả hai cách, và sẽ có lời khuyên của mình nên sử dụng cách nào ở bên dưới.

Cách 1: dùng Extra truyền nhận dữ liệu bằng Extra là cách dễ nhất.
Gửi Dữ Liệu: 

Đầu tiên, để gửi dữ liệu bằng Extra. Sau khi khai báo Intent và trước khi bạn dùng nó để kích hoạt activity nào đó, bạn có thể sử dụng các phương thức được nạp chồng của nó để gửi dữ liệu. Các phương thức đó có chung một tên là putExtra().

Bạn nhớ là các phương thức putExtra() này không có s đằng sau Extra nhé. Extra có s sẽ dành cho mục Bundle dưới đây.

Với mỗi putExtra() như vậy, tham số đầu tiên chính là key mà mình có nói trên kia. Tham số thứ hai tương tự chính là value. Phương thức này được nạp chồng làm nhiều bản để bạn dễ dàng sử dụng từng loại value mà bạn muốn. Tuy nhiên bạn đừng để ý hai kiểu value là Parcelable và Serializable, hai kiểu này hơi phức tạp một chút, chúng ta sẽ có một bài viết riêng về hai kiểu này khi thích hợp.

Đoạn code sau ví dụ cách để đặt dữ liệu vào Intent bằng Extra.

Intent intent = new Intent(this, ContactActivity.class);
intent.putExtra("Key_1", "Truyền một String");  // Truyền một String
intent.putExtra("Key_2", 5);                    // Truyền một Int
intent.putExtra("Key_3", true);                 // Truyền một Boolean
startActivity(intent);

Nhận Dữ Liệu

Khi này, theo như ví dụ trên thì ContactActivity sẽ được kích hoạt với dữ liệu là ba cặp key/value được truyền qua. Ở phương thức onCreate() hoặc bất cứ chỗ nào của ContactActivity, bạn đều có thể lấy bất cứ cặp key/value nào ra dùng. Bằng cách gọi đến getXxxExtra().

Mình ghi chung là Xxx, vì Xxx này sẽ được bạn thay thế bằng kiểu dữ liệu phù hợp với keybên “đóng gói”, như getBooleanExtra()getStringExtra()getIntExtra(),… Dĩ nhiên tham số name truyền vào phương thức này phải đúng là key bên đóng gói luôn.

Một số phương thức cần phải có tham số thứ hai, tham số này chính là dữ liệu mặc định nếu như hệ thống không tìm thấy dữ liệu với key mà bạn cung cấp. Việc cung cấp tham số thứ hai này tránh một số lỗi xảy ra đối với chương trình của chúng ta.

Đoạn code sau minh họa cách lấy dữ liệu ra khỏi Intent bằng Extra ở onCreate() của Activity. Bạn có thể thấy từng cặp key/value khớp với khi bạn đặt dữ liệu vào trên kia.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact);
 
    // Các dòng code khác...
 
    Intent intent = getIntent();
    String value1 = intent.getStringExtra("Key_1");
    int value2 = intent.getIntExtra("Key_2", 0);
    boolean value3 = intent.getBooleanExtra("Key_3", false);
}

Cách 1: dùng Bundle truyền nhận dữ liệu.

Thực ra Bundle và Extra không khác gì nhau hết. Nếu như Extra trên kia sẽ “xé lẻ” dữ liệu ra và gởi theo từng dòng. Thì Bundle sẽ giúp bạn “đóng gói” dữ liệu lại và gởi nguyên kiện. Tất nhiên Bundle sẽ tiện hơn trong trường hợp bạn muốn gởi cùng một bộ dữ liệu đến nhiều Activity khác nhau.

Ngoài nhiệm vụ đóng gói dữ liệu để truyền qua lại giữa các Activity ở bài học này, thì Bundle còn dùng trong một số mục đích khác, đơn cử như truyền dữ liệu qua Fragment mà bạn sẽ được biết ở bài sau. Nên tốt hơn hết bạn nên học cách sử dụng Bundle ngay từ bài này nhé.
Gửi Dữ Liệu

Chỉ có phát sinh vài dòng code so với Extra trên kia thôi, đầu tiên là dòng tạo ra Bundle. Sau đó vẫn là các dòng đặt dữ liệu vào Bundle, các dòng này có hơi khác với các dòng đặt dữ liệu vào Extra một chút, nếu với Extra bạn dùng các phương thức nạp chồng với cùng một tên putExtra() thì với Bundle bạn phải dùng đúng phương thức putXxx() với Xxx là kiểu dữ liệu bạn cần dùng.
Khi Bundle đã chứa đủ dữ liệu, bạn cần phải đặt Bundle này vào trong Intent bằng một dòng code putExtras() (nhớ là có s nhé). Bạn xem code như sau.

Intent intent = new Intent(this, ContactActivity.class);
Bundle bundle = new Bundle();
bundle.putString("Key_1", "Truyền một String"); // Truyền một String
bundle.putInt("Key_2", 5);                      // Truyền một Int
bundle.putBoolean("Key_3", true);               // Truyền một Boolean
intent.putExtras(bundle);
startActivity(intent);

Nhận Dữ Liệu

Cũng tương tự như bên gửi thôi, nếu đã gửi theo Bundle, thì bên nhận cũng sẽ nên nhận theo Bundle trước rồi mới lấy từng dữ liệu ra dùng. Để lấy Bundle ra khỏi Intent thì chúng ta có phương thức getExtras().

Sau khi lấy Bundle ra khỏi Intent, việc tiếp theo sẽ gọi đến các phương thức getXxx() của nó. Các phương thức này của Bundle cũng giống như các phương thức getXxxExtra() của Extratrên kia. Chỉ khác một chỗ getXxx() của Bundle thường có hai phương thức nạp chồng, giúp bạn linh động hơn. Thường thì bạn nên dùng getXxx() với hai tham số, như vậy bạn có thể định nghĩa được giá trị mặc định cho từng phương thức khi mà nó không tìm thấy dữ liệu từ key mà bạn cung cấp, giúp tránh một số lỗi không cần thiết.
Để chắc chắn thì khi nhận dữ liệu với Bundle, bạn nên kiểm tra xem Bundle đó có tồn tại hay không (kiểm tra khác null) trước.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact);
 
    // Các dòng code khác...
 
    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    if (bundle != null) {
        String value1 = bundle.getString("Key_1", "");
        int value2 = bundle.getInt("Key_2", 0);
        boolean value3 = bundle.getBoolean("Key_3", false);
    }
}

Ngoài ra,chúng ta cũng có thể truyền Đối Tượng qua lại giữa các Activity, các đối tượng này phải được Serialize

Trong trường hợp truyền đối tượng thì ta dùng putSerializable và getSerializable

Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có 2 Activity. MainActivity cho người sử dụng nhập 2 số, sau đó click vào Button “Tính”, chuyển qua SumActivity nhận 2 số truyền từ MainActivity, sau đó, thực hiện phép tính tổng rồi hiển thị ra màn hình SumActivity.Tiến hành tạo project, vào thư mục  res /layout -> activity_main.xml  thiết kế giao diện sau:

Bước 1: Tạo một project tên là SumTwoNumberFile->New->Android Application Project điền các thông tin ->Next ->Finish

Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="hiepsiit.com.sumtwonumber.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#f00"
        android:gravity="center"
        android:text="Tổng Hai Số" />

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
       	android:stretchColumns="*"
        android:layout_marginTop="26dp" >

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/txtNuma"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Nhập số a:" />

            <EditText
                android:id="@+id/edtNuma"
                android:layout_width="180dp"
                android:layout_height="wrap_content"
                android:text="" >

                <requestFocus />
            </EditText>

        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
             <TextView
                android:id="@+id/txtNumb"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Nhập số b:" />

            <EditText
                android:id="@+id/edtNumb"
                android:layout_width="180dp"
                android:layout_height="wrap_content"
                android:text="" >

                <requestFocus />
            </EditText>
            
        </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/btnSubmit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_column="1"
                android:text="Tính" />

        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </TableRow>
    </TableLayout>

</RelativeLayout>

Bước 3: Mở src -> package -> MainActivity.java
Trong bước này chúng ta khởi tạo các Widget. Sau đó, thiết lập sự kiện cho button, khi người sử dụng click vào button “Tính” này chúng ta lấy giá trị nhập vào và  chuyển qua SumActivity nhận 2 số truyền từ MainActivity

package hiepsiit.com.sumtwonumber;

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

public class MainActivity extends Activity {
	EditText edtNuma, edtNumb;
	Button btnSum;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edtNuma	=	(EditText)	findViewById(R.id.edtNuma);
		edtNumb	=	(EditText)	findViewById(R.id.edtNumb);
		btnSum	=	(Button)	findViewById(R.id.btnSubmit);
		btnSum.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			 try{
			 Intent myIntent	=	new Intent(getApplication(),SumActivity.class);
			 int a	=	Integer.parseInt(edtNuma.getText().toString());
			 int b	=	Integer.parseInt(edtNumb.getText().toString());
			 Bundle myBundle	=	 new Bundle();
			 myBundle.putInt("soa", a);
			 myBundle.putInt("sob", b);
			 myIntent.putExtra("mysum", myBundle);
			 startActivity(myIntent);
			 }
			 catch(Exception ex){
				
			 }
			}
		});
	}

}

Bước 4: Tạo một mới Activity Android mới đặt tên SumActivity.  Mở res -> layout -> xml (hoặc) activity_sum.xml và thêm code.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="hiepsiit.com.sumtwonumber.SumActivity" >

    <TextView
       android:id="@+id/txtResult"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff00"
        android:textSize="45px"
        android:text="@string/hello_world" />

</RelativeLayout>

Bước 5: Mở src -> package -> SumActivity.java
Trong bước này chúng ta khởi tạo TextView, nhận dữ liệu từ MainActivity, tính tổng 2 số xuất ra TextView

package hiepsiit.com.sumtwonumber;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class SumActivity extends Activity {
	TextView txtResult;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sum);
		txtResult	=	(TextView)findViewById(R.id.txtResult);
		Intent myIntent = getIntent();
		Bundle	myBunble=	myIntent.getBundleExtra("mysum");
		int a	=	myBunble.getInt("soa");
		int b 	=	myBunble.getInt("sob");
		int c	=	a	+	b;
		txtResult.setText("Tổng 2 số là: "+c);
	}

}

Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 4.2 sử dụng minimum sdk 8 and target sdk 21.

Kết quả khi chạy ứng dụng:

Nhập vào 2 số và click vào “Tính”:

Kết quả:

2. Lấy kết quả trả về từ một Activity.

Trong Android, việc truyền và nhận dữ liệu và kết quả giữa các Activity rất hay được sử dụng, và đây cũng là một trong những bài học cơ bản đầu tiên mà mỗi bạn khi bắt đầu tìm hiểu về lập trình Android đều cần biết.

Bằng cách sử dụng startActivityForResult(Intent intent, int requestCode) thay vì dùng startActivity() bạn có thể start một Activity và sau đó nhận kết quả trả về từ Activity đó thông qua phương thức onActivityResult().

 – Chúng ta sẽ dựa vào requestCodeID và resultCode để xử lý.

– Việc tạo Intent trong trường hợp này cũng y xì như trường hợp trước. Nó chỉ khác hàm gọi :

Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có  2 Activity Android

– Khi nhập số và nhấn “Lưu bình phương” thì nó sẽ truyền số này qua MainActivity và cập nhật ListView với số này là nhân bình phương.

– Khi nhập số và nhấn “lưu số gốc” thì nó sẽ truyền số này qua MainActivity và cập nhật ListView với đúng số gốc này.

– Bạn chú ý là phải đóng Dialog ngay, vì nếu không đóng thì onActivityResult sẽ không sảy ra. onActivityResult chỉ sảy ra trong foreground life time.

– Tiến hành tạo project, vào thư mục  res /layout -> activity_main.xml  thiết kế giao diện sau:

Bước 1: Tạo một project tên là IntentResultFile->New->Android Application Project điền các thông tin ->Next ->Finish

Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/LinearLayout1"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".MainActivity" >
 
<Button
 android:id="@+id/btnopenactivity"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="Mở Activity Nhập Dữ Liệu" />
 
<ListView
 android:id="@+id/lvdata"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 </ListView>
 
</LinearLayout>

Bước 3: Mở src -> package -> MainActivity.java
Trong bước này chúng ta khởi tạo các Widget, thiết lập sự kiện cho Button. Cũng trong bước này chúng ta thiết lập phương thức onActivityResult(int requestCode, int resultCode, Intent data) để nhận giá trị từ các Activity Android khác khi kết thúc.

Ta kiểm tra requestCode và resultCode cho đúng, requestCode là bên MainActivity dùng để triệu gọi một Activity bất kỳ nào đó

resultCode là kết quả trả về trong hàm setResult(resultcode, intent); của sub Activity nào đó. Hàm này cho chúng ta biết kết quả trả về là code nào và đồng thời cho ta biết luôn Intent của nó. Dựa vào Intent này mà trong onActivityResult ta có thể dễ dàng lấy thông số ra (đối số thứ 3)

package hiepsiit.com.intentresult;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity {
	public static final int REQUEST_CODE_INPUT=113;
	public static final int RESULT_CODE_SAVE1=115;
	public static final int RESULT_CODE_SAVE2=116;
	Button btnInputData;
	ListView lvData;
	ArrayList<Integer>arrData=new ArrayList<Integer>();
	ArrayAdapter<Integer>adapter=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btnInputData	=	(Button) findViewById(R.id.btnopenactivity);
		btnInputData.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//Mở Activity với REQUEST_CODE_INPUT
				Intent	intent	=	new 	Intent(getApplicationContext(),ActivityInput.class);
				 //gọi startActivityForResult
				startActivityForResult(intent, REQUEST_CODE_INPUT);
			}
		});
		//đoạn code dưới này học nhiều rồi, ko nói lại
		 lvData=(ListView) findViewById(R.id.lvdata);
		 adapter=new ArrayAdapter<Integer>
		 (this,
		 android.R.layout.simple_list_item_1,
		 arrData);
		 lvData.setAdapter(adapter);		
		
	}
	 /**
	 * Xử lý kết quả trả về ở đây
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		//Kiểm tra có đúng requestCode =REQUEST_CODE_INPUT hay không
		 //Vì ta có thể mở Activity với những RequestCode khác nhau
		 if(requestCode==REQUEST_CODE_INPUT)
		 {
			 //Kiểm trả ResultCode trả về, cái này ở bên InputDataActivity truyền về
			 //có nó rồi thì xử lý trở lên thông thường
			 switch(resultCode)
			 {
			 case RESULT_CODE_SAVE1:
			 //giá trị từ InputDataActivity
			 int v1= data.getIntExtra("data", 0);
			 arrData.add(v1*v1);
			 adapter.notifyDataSetChanged();
			 break;
			 case RESULT_CODE_SAVE2:
			 //giá trị từ InputDataActivity
			 int v2= data.getIntExtra("data", 0);
			 arrData.add(v2);
			 adapter.notifyDataSetChanged();
			 break;
			 }
		 }
	}
	
}

Bước 4: Tạo một mới Activity Android mới đặt tên ActivityInput.  Mở res -> layout -> xml (hoặc) activity_input.xml và thêm code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/LinearLayout1"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".InputDataActivity" >
 
<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 
<TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Nhập số:" />
 
<EditText
 android:id="@+id/editNumber"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:ems="10" >
 
<requestFocus />
 </EditText>
 
</LinearLayout>
 
<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 
<Button
 android:id="@+id/btnSave1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:text="Lưu Bình Phương" />
 
<Button
 android:id="@+id/btnSave2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:text="Lưu Số gốc" />
 
</LinearLayout>
 
</LinearLayout>

Bước 5: Mở src -> package -> SumActivity.java
Trong bước này chúng ta khởi tạo Widget , nhận dữ liệu từ ActivityInput. Để gởi kết quả về cho MainActivity chúng ta dùng hàm  setResult().
 

package hiepsiit.com.intentresult;

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

public class ActivityInput extends Activity {
	Button btnSave1,btnSave2;
	EditText editNumber;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_input);
		editNumber	=	(EditText)	findViewById(R.id.editNumber);	
		btnSave1	=	(Button) findViewById(R.id.btnSave1);
		btnSave2	=	(Button) findViewById(R.id.btnSave2);
		btnSave1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				sendToMain(MainActivity.RESULT_CODE_SAVE1);	
			}
		});
		btnSave2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				sendToMain(MainActivity.RESULT_CODE_SAVE2);	
			}
		});
	}
	 /**
	 * hàm xử lý gửi kết quả về mainactivity
	 * khi hàm này được gọi thì lập tức onActivityResult
	 * ở MainActivity sẽ sảy ra đem theo ResultCode và Intent
	 * @param resultcode
	 */
	 public void sendToMain(int resultcode)
	 {
	 Intent intent=getIntent();
	 int value= Integer.parseInt(editNumber.getText()+"");
	 intent.putExtra("data", value);
	 setResult(resultcode, intent);
	 finish();
	 }
}

Bước 5: Cấu hình  ActivityInput dưới dạng Dialog: Mở Manifest để cấu hình như hình bên dưới: 

Chọn Theme: @android:style/Theme.Holo.Dialog.Tại màn hình trên ta chọn đúng Activity muốn làm Dialog rồi tìm tới thuộc tính Theme, nhấn vào nút “Browse”…:

Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 4.2 sử dụng minimum sdk 11 and target sdk 21.

Kết quả khi chạy ứng dụng:

Sau đó click vào “Mở  Activity Nhập Dữ Liệu”:

Nhập số cần tính chọ nút “Lưu Bình Phương”: