Android Tutorial : Using Intent to move from one activity to another and sending data via putExtra

We talked in a previous tutorial on using Buttons and how to trigger an action following a button click.
This tutorial is the fulfillment of the previous tutorial:Android tutorial for beginners:using Button, Listener and Toast .

In the previous tutorial we have seen how to use a button and how to add listener to the button to trigger actions.We have seen how to show a toast (a short pop up message) after clicking the button.

In this tutorial we will see how to move from an activity to another after clicking the button.
Create a new project in your eclipse (File ==> New ==> Android Application Poject) and give the name of 'Intention' to your project.

In your activity_main.xml put this 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" tools:context="${relativePackage}.${activityClass}" > <Button android:id="@+id/intent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="Click me !" /> </RelativeLayout>

In your MainActivity.java put this code :


import android.app.Activity; 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; public class MainActivity extends Activity { Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button)findViewById(R.id.intent); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); } }

Now add a new android xml file in your layout folder and give it  the name of second_activity.xml :Right-click on the layout  folder ==>New==>Android Xml File.  
Put this code in your second_activity.xml file : 


<?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" > <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="TextView" /> </LinearLayout>
After that add a new activity (java class) in your package in the src folder and give it this name 'Second'.
This new class (Second.java) in which we can place our UI with setContentView(View) must inherit the Activity class and must contain the method "onCreate()"  to call (with setContentView(View)) our layout "second_activity.xml" recently added.

The Second.java class must contain this code:
import android.app.Activity; import android.os.Bundle; public class Second extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); } }

Do not forget to declare your new activity (Second) in the AndroidManifest.xml file.
On the inside of the xml tag <application> .... </application> of the AndroidManifest.xml file put this code:

<activity android:name=".Second" android:label="@string/app_name" > </activity>

Your AndroidManifest.xml will be similar to this code :

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.intention" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" 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=".Second" android:label="@string/app_name" > </activity> </application> </manifest>

Now what we want to do is to move from the "MainActivity" to "Second" ,we must use an Intent to do this.

What is Intent?

The intents are one of the cornerstones of the platform. We can compare them to actions or even intentions, they can interact through the system from channels that are dedicated to them. When your phone receives a call, the platform launches Intent indicating an incoming call, and for SMS.
Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining the components you are targeting. For example, via the startActivity() method you can define that the intent should be used to start an activity.
An intent can contain data via a Bundle. This data can be used by the receiving component.
The following code demonstrates how you can start another activity via an intent.
Intent intention = new Intent(MainActivity.this, Second.class);
startActivity(intention);
So now we have to add these two lines in the onClick() method of our Button to move from MainActivity to Second and the MainActivity.java class will have this code :

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; public class MainActivity extends Activity { Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button)findViewById(R.id.intent); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intention = new Intent(MainActivity.this, Second.class); startActivity(intention); } }); } }
Now run your project and you'll see what will happen when you click the button "Click me!".

But if we want to send data from the main activity to the second activity what shall we do?
We will see this, we will create a String variable- in the MainActivity.java- in which we will put a text.
This text should be displayed in a toast after moving from the first activity to the second.So the value of this String  must be sent in the Intent with the "putExtra" method.
We will begin with declaring our  String variable.

String value="Hello World!!!!";

We need to put this variable in our method putExtra () after the declaration of intent.

intention.putExtra("send", value);

putExtra() adds extended data to the intent. It has two parameters, first one specifies the name which of the extra data,and the second parameter is the data itself.
So our MainActivity.class will have this code :

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; public class MainActivity extends Activity { Button btn; String value="Hello World!!!!"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button)findViewById(R.id.intent); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intention = new Intent(MainActivity.this, Second.class); intention.putExtra("send", value); startActivity(intention); } }); } }


The question now arises: how the class "Second.java" will retrieve the data that was sent? We must create a Bundle in the Second.java class

Bundle extras= getIntent().getExtras();
getExtra() fetches data which was added using putExtra().
Bundle is basically a mapping from String values to various Parcelable types.
getIntent() returns the intent that started this activity.
and after that we must create a String variable that fetch the string passed with intent and we will create a Toast to show us the content of this string.
if(extras != null) { String newString=extras.getString("send"); Toast.makeText(Second.this,newString, Toast.LENGTH_LONG).show();
}


So the Second.java class will have this code :


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

public class Second extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Bundle extras= getIntent().getExtras();
if(extras != null)
 
{    
String  newString=extras.getString("send");
 Toast.makeText(Second.this,newString, Toast.LENGTH_LONG).show();
}
}
}


Commentaires

Enregistrer un commentaire

Your comment will be reviewed by moderators

Posts les plus consultés de ce blog

Ionic 2 : Envoie d'une image vers un serveur web à l'aide de PHP et Angular 2

Premier tutoriel avec Arduino et Proteus ISIS

Login et password ,formulaire d'authentification sous android avec mysql et json