NAVIGATION - SEARCH

Android - Passing Data or Send Receive Data Between Activities

Your app can have multiple activities and you may need to pass some data to different activities. For e.g., you want to launch another activity to display all hotels on a Google map, so you pass latitude longitude to another activity. When the user has finished seeing the hotels data, the data also needs to be passed back to the calling activity like which hotel information was viewed.

You can use the Intent class to pass data to another activity. To pass primitive data types like string, int, etc. to another activity, you can use the putExtra() method or a bundle object which is like a dictionary object and you can specify key/value pairs. When you start another activity using the Intent object, the data attached to the Intent object is passed to the destination activity. Use the startActivityForResult() method to get data back from called activity. The code below shows both the methods:

package com.youritbuddy.demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity 
{
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	
	public void onBtnClick1(View view) 
	{
		Intent i = new Intent("com.youritbuddy.demoActivity");
		
		i.putExtra("lat", "78.1234");
		i.putExtra("lng", "78.1234");
		
		startActivityForResult(i, 1);
	}
	
	public void onBtnClick2(View view) 
	{
		Intent i = new Intent("com.youritbuddy.demoActivity");
		
		Bundle extras = new Bundle();
		extras.putString("lat", "78.1234");
		extras.putString("lng", "78.1234");
	
		i.putExtras(extras);
		
		startActivityForResult(i, 2);
	}
}

The startActivityForResult() method takes an Intent object and a request code. This request code is an integer value that is greater than or equal to zero and is used to identify returning activities as more than one activity can be called. To retrieve data that was passed to target activity, use the getIntent() method to obtain the instance of the Intent object that was passed to it.

package com.youritbuddy.demo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class demoActivity extends Activity 
{
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
		
		//TO RETRIEVE DATA PASSED USING putExtra() METHOD
		
		Toast.makeText(this, getIntent().getStringExtra("lat"), Toast.LENGTH_SHORT).show();		
		Toast.makeText(this, getIntent().getStringExtra("lng"), Toast.LENGTH_SHORT).show();
		
		//TO RETRIEVE DATA PASSED USING BUNDLE OBJECT
		
		Bundle bundle = getIntent().getExtras();
		Toast.makeText(this, bundle.getString("lat"), Toast.LENGTH_SHORT).show();
		Toast.makeText(this, bundle.getString("lng"), Toast.LENGTH_SHORT).show();
	}
}

To pass data back to the calling activity, create an Intent object and set the values as shown earlier. To pass the result back to the calling activity, use the setResult() method, as shown in the following code:

package com.youritbuddy.demo;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class demoActivity extends Activity 
{
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
		
		//TO RETRIEVE DATA PASSED USING putExtra() METHOD
		
		Toast.makeText(this, getIntent().getStringExtra("lat"), Toast.LENGTH_SHORT).show();		
		Toast.makeText(this, getIntent().getStringExtra("lng"), Toast.LENGTH_SHORT).show();
		
		//TO RETRIEVE DATA PASSED USING BUNDLE OBJECT
		
		Bundle bundle = getIntent().getExtras();
		Toast.makeText(this, bundle.getString("lat"), Toast.LENGTH_SHORT).show();
		Toast.makeText(this, bundle.getString("lng"), Toast.LENGTH_SHORT).show();
	}

	public void onBtnClick(View view) 
	{
		Intent i = new Intent();
		
		i.putExtra("hotelname", "5 Star Deluxe");
		i.setData(Uri.parse("http://www.5starhoteltest.com"));
		
		setResult(RESULT_OK, i);
		
		finish();
	}
}

The RESULT_OK constant indicate to the calling activity that the returned data should be processed or if you want to notify to ignore returned data then you can use the RESULT_CANCELLED constant. It is upto you on how do you want to interpret this data and these two constants serves as an indication. Implement the onActivityResult() method in the calling activity to process any data that was returned from called activity. The request code that you passed earlier is to ensure that you are getting the result from the correct activity.

package com.youritbuddy.demo;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity 
{
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	
	public void onBtnClick1(View view) 
	{
		Intent i = new Intent("com.youritbuddy.demoActivity");
		
		i.putExtra("lat", "78.1234");
		i.putExtra("lng", "78.1234");
		
		startActivityForResult(i, 1);
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == 1) 
		{
			if (resultCode == RESULT_OK) 
			{
				Toast.makeText(this, data.getStringExtra("hotelname"), Toast.LENGTH_SHORT).show();
				Uri url = data.getData();
				Toast.makeText(this, url.toString(), Toast.LENGTH_SHORT).show();
			}
		}
	}
}

If setData() method of intent object was used then use the getData() method to retrieve data.

The above method is used to pass and retrieve primitive type datas like string and integers. However you may also pass objects between activities thus giving you more control. For e.g. you may pass a customer object having id, name, email, address, etc. to another activity for processing. You just need to ensure that the class object implements the Serializable base class.

package com.youritbuddy.demo;

import java.io.Serializable;

public class CustomerData implements Serializable 
{
	private static final long VersionID = 1L;
	String _name;
	String _email;
	String _address;

	public void setName(String name) 
	{
		_name = name;
	}

	public String Name() 
	{
		return _name;
	}

	public void setEmail(String email) 
	{
		_email = email;
	}

	public String Email() 
	{
		return _email;
	}
	
	public void setAddress(String address) 
	{
		_address = address;
	}

	public String Address() 
	{
		return _address;
	}
}

To pass an object to another activity, use the putExtra() method:

public void onBtnClick(View view) 
{
	Intent i = new Intent("com.youritbuddy.demoActivity");
	
	CustomerData objCustomerData = new CustomerData();
	
	objCustomerData.setName("Jack Wills");
	objCustomerData.setEmail("jackwills@noemail.com");
	objCustomerData.setAddress("Custer Street New York");
	
	i.putExtra("objCustomerData", objCustomerData);
	
	startActivityForResult(i, 1);
}

To retrieve the object passed to another activity, use the getSerializableExtra() method of the Intent object, passing it the key that you set earlier in the putExtra() method. Then, typecast the result returned by this method to the CustomerData class and assign it to a variable of this type:

@Override
public void onCreate(Bundle savedInstanceState) 
{
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_second);
		
	CustomerData obj = (CustomerData)getIntent().getSerializableExtra("objCustomerData");
	
	Toast.makeText(this, obj.Name(), Toast.LENGTH_SHORT).show();
	Toast.makeText(this, obj.Email(), Toast.LENGTH_SHORT).show();
	Toast.makeText(this, obj.Address(), Toast.LENGTH_SHORT).show();
} 

The above article has explained about how to pass data across activities in an Android app. You may extend these examples to real world scenarios.

Add comment