Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How data is shared between multiple activities in Android

In this article, we will learn about the data sharing between multiple android application activities.

We know that all the activities in android are managed by pure java classes. Hence, the communication between activities will also be achieved with these classes by using their class objects with few additional mechanisms.

Let’s start with an android application example of data sharing. This application has two xml layouts and one string values xml file:

This layout file has one <EditText /> attribute and two <Button /> attributes with one <TextView/> attribute as listed below:

Listing 1: get.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    	xmlns:android="http://schemas.android.com/apk/res/android"
		android:id="@+id/relLayout"
		android:layout_width="match_parent"
		android:layout_height="match_parent">
	<EditText
	    android:layout_height="wrap_content"
		android:layout_width="match_parent"
		android:id="@+id/etSend"
		android:hint="@string/relLayout"/>
	<Button
		android:layout_below="@id/etSend"
	    android:layout_alignParentRight="true"
	    android:text="@string/bSend"
	    android:id="@+id/bSA"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content" />

	<Button
	    android:id="@+id/bSAFR"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:layout_alignTop="@id/bSA"
	    android:paddingLeft="2dp"
	    android:text="@string/bSAFR" />

	<TextView
	    android:layout_below="@id/bSAFR"
	    android:text="@string/tvSAFR"
	    android:id="@+id/tvGot"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"/>
</RelativeLayout>

This layout has two <TextView/> attributes, one <RadioButtonGroup/> attribute that has three <RadioButton/> attributes, one <Button/> attribute as listed below:

Listing 2: send.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="match_parent"
	android:layout_height="match_parent">
	<TextView android:layout_height="wrap_content" android:text="@string/tvSend1"
		android:textAppearance="?android:attr/textAppearanceSmall"
		android:layout_width="wrap_content" android:id="@+id/tvQ"></TextView>
	<RadioGroup android:id="@+id/rgAnswers"
		android:layout_width="wrap_content" android:layout_height="wrap_content">
		<RadioButton android:text="@string/option1" android:id="@+id/rCrazy"
			android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
		<RadioButton android:text="@string/option2" android:id="@+id/rSexy"
			android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
		<RadioButton android:text="@string/option3" android:id="@+id/rBoth"
			android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
	</RadioGroup>
	<Button android:text="@string/ret" android:id="@+id/bReturn"
		android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
	
	<TextView android:text="@string/tvSend2" android:id="@+id/tvText"
		android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>

</LinearLayout>

There is one more xml file, which is string.xml. This file has all values for layout xml files string variables.

Listing 3: string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name = "bSAFR">StartActivityResult</string>
    <string name = "relLayout">Type Something</string>
    <string name = "tvSAFR">TextView</string>
    <string name = "bSend">Send Data</string>
    <string name = "option1">Option1</string>
    <string name = "option2">Option2</string>
    <string name = "option3">Option3</string>
    <string name = "ret">Back</string>
    <string name = "tvSend1">Umesh</string>
    <string name = "tvSend2">Kushwanshi</string>
</resources>

These xml layouts are being managed by two activity classes defined in two java files.

The data sharing between activities is achieved using Bundle Class of android.os package.

We have to create an instance of android.os.Bundle class, and put the sharable data into this instance object as mapping object using putString() method of this class. This method accepts two parameters named ‘key’ and ‘value’:

Bundle bundle = new Bundle();
bundle.putString(“key”, “MyDataString”);

Once the bundle is ready, create an intent and send this bundle to receiver activity as follows:

Intent a = new Intent(Sender.this, Receiver.class);
a.putExtra(bundle);
startActivity(a);

In order to receive this data in the receiver class, we have to create an instance of bundle class once again. Now, We have to call another method of this class named getString(). This method access a key as string parameter. This key should match with the keys defined in bundle (array) of sender class.

Bundle getData = getIntent().getExtras();
String getData = getData.getString(“key”);
editText.setText(getData);

These java classes are listed as follows:

Listing 4: Sender.java

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

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;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Sender extends Activity implements OnClickListener {

	Button start, btnFor;
	EditText et;
	TextView getQ;
	RelativeLayout rl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.get);
		initialize();
		rl = (RelativeLayout)findViewById(R.id.relLayout);
		AdView ad = new AdView(Sender.this, AdSize.BANNER, "YOUR_ADMOB_ID");
		rl.addView(ad);
		ad.loadAd(new AdRequest());
	}

	private void initialize() {
		// TODO Auto-generated method stub
		start = (Button) findViewById(R.id.bSA);
		btnFor = (Button) findViewById(R.id.bSAFR);
		et = (EditText) findViewById(R.id.etSend);
		getQ = (TextView) findViewById(R.id.tvGot);
		start.setOnClickListener(this);
		btnFor.setOnClickListener(this);
	}

	public void onClick(View arg0) {
	       switch (arg0.getId()) {
		case R.id.bSA:
			String bread = et.getText().toString();
			Bundle basket = new Bundle();
			basket.putString("key", bread);
			Intent a = new Intent(Sender.this, Receiver.class);
			a.putExtras(basket);
			startActivity(a);
			break;
		case R.id.bSAFR:
			Intent i = new Intent(Sender.this, Receiver.class);
			startActivityForResult(i, 0);
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent Sender) {
	
	super.onActivityResult(requestCode, resultCode, Sender);
		if (resultCode == RESULT_OK){
			Bundle basket = Sender.getExtras();
			String s = basket.getString("answer");
			getQ.setText(s);
		}
	}

}

Listing 5: Receiver.java

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class Receiver extends Activity implements OnClickListener, OnCheckedChangeListener {

	TextView q, t;
	Button getDataBack;
	RadioGroup getList;
	String getData, setData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.send);
		initialize();
		SharedPreferences getData = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		String et = getData.getString("name", "Travis is...");
		String values = getData.getString("list", "4");
		if(values.contentEquals("1")){
			q.setText(et);
		}
	}

	private void initialize() {
		q = (TextView) findViewById(R.id.tvQ);
		t = (TextView) findViewById(R.id.tvText);
		getDataBack = (Button) findViewById(R.id.bReturn);
		getDataBack.setOnClickListener(this);
		getList = (RadioGroup) findViewById(R.id.rgAnswers);
		getList.setOnCheckedChangeListener(this );
	}

	public void onClick(View arg0) {
		Intent person = new Intent();
		Bundle backpack = new Bundle();
		backpack.putString("answer", setData);
		person.putExtras(backpack);
		setResult(RESULT_OK, person);
		finish();
	}

	public void onCheckedChanged(RadioGroup arg0, int arg1) {
		switch (arg1) {
		case R.id.rCrazy:
			setData = "Probably right!";
			break;
		case R.id.rSexy:
			setData = "Definitely right!";
			break;
		case R.id.rBoth:
			setData = "Spot On!";
			break;
		}
		t.setText(setData);
	}
}

The first class

There is one more xml file, which is the android application configuration file, named AndroidManifest.xml file.

Listing 6: AndroidMenifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ndapp"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/calc_icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!-- This is main activity loader -->
        <activity
            android:name=".Sender"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Receiver"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.example.ndapp.RECEIVER />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity> 
        </application>
</manifest>

Output:

Displays the output

Figure1: Displays the output

Conclusion

We understand how to share data between two android activities in Android. See you next time.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login