Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Passing extra items with Intents

Lab - 4
Creating new Activities
What is an Activity?

An activity is a single, focused thing that the user can do. Almost all activities interact with the
user, so the Activity class takes care of creating a window for you in which you can place your UI
with setContentView(View). While activities are often presented to the user as full-screen windows,
they can also be used in other ways: as floating windows (via a theme with windowIsFloating set)
or embedded inside of another activity (using ActivityGroup). There are two methods almost all
subclasses of Activity will implement:

• onCreate(Bundle) is where you initialize your activity. Most importantly, here you will
usually call setContentView(int) with a layout resource defining your UI, and using
findViewById(int) to retrieve the widgets in that UI that you need to interact with
programmatically.
• onPause() is where you deal with the user leaving your activity. Most importantly, any
changes made by the user should at this point be committed (usually to the
ContentProvider holding the data).

To be of use with Context.startActivity(), all activity classes must have a corresponding <activity>
declaration in their package's AndroidManifest.xml.

Activity Lifecycle

Activities in the system are managed as an activity stack. When a new activity is started, it is placed
on the top of the stack and becomes the running activity -- the previous activity always remains
below it in the stack, and will not come to the foreground again until the new activity exits.

An activity has essentially four states:

If an activity in the foreground of the screen (at the top of the stack), it is active or running.

If an activity has lost focus but is still visible (that is, a new non -full-sized or transparent activity
has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains
all state and member information and remains attached to the window manager), but can be killed
by the system in extreme low memory situations.

If an activity is completely obscured by another activity, it is stopped. It still retains all state and
member information, however, it is no longer visible to the user so its window is hidden and it will
often be killed by the system when memory is needed elsewhere.

If an activity is paused or stopped, the system can drop the activity from memory by either asking
it to finish, or simply killing its process. When it is displayed again to the user, it must be
completely restarted and restored to its previous state.

The following diagram shows the important state paths of an Activity. The square rectangles
represent callback methods you can implement to perform operations when the Activity moves
between states. The colored ovals are major states the Activity can be in.
Task 1: (5 marks)

Create an application that will launch a new activity when a user click a button.

Program Steps

1. Create a new project selecting > File > New > New Android Project.
2. Drag and drop the controls as show in the figure and the change the layout xml accordingly.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="10dp" android:paddingRight="10dp"
tools:context=".AcitivtyDemo" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Second Activity" />
</RelativeLayout>

3. Click File > New > Class


4. Name the new class “SecondActivity.java” and extend it with android.app.Activity. Click
Finish.

5. Click File > New > Android XML File.


6. Change the fields as shown in the figure and click Finish
7. Drag a text view from the widget and change its text to “This is second Activity”.
8. Open the SecondActivity.Java and update the code as shown in the snippet.
public class SecondActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
}
}
9. This second activity should be registered in the Mainfest file so that android understand that
the application contain second activity.
10. Open AndroidMainfest.xml file and registered the activity by adding the <activity></
activity> tags.

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samd.activitydemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.samd.activitydemo.AcitivtyDemo"
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=".secondactivity"></activity>
</application>
</manifest>

11. To start second activity add an event on the button. To do so open the ActivityDemo.Java
and change the code as shown in the snippet.
public class ActivityDemo extends Activity {

private Button btnSecondActivity;


private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitydemo);
btnSecondActivity = (Button) findViewById(R.id.button1);
btnSecondActivity.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
intent = new Intent(ActivityDemo.this,
SecondActivity.class);
startActivity(intent);
}
});
}
12. Launch the application and click “Second Activity Button” the second activity will launched
as shown in the figures.

Task 2: (5 marks)
• Create a view for entering two values along with a button to send the values.
• Keep overall layout of the view as ‘RelativeLayout’.
• At the top of the view, insert a ‘TextView’ that has width equal the width of the
screen.
• Below this text view insert another ‘TextView’ and an ‘EditView’ both at the same
height and each covering 50% of the width of the screen.
• Repeat the above step once more.
• Add the button below the rest of the controls and set its width equal to the width
of the screen.

Procedure:
• Drag and drop the controls required onto the form or create using the xml code.
• The first ‘TextView’ can be set quite easily by just setting the width equal to
‘match_parent’.
• For the ‘TextView’ and the ‘EditText’ that have to be placed side by side we need
to create another ‘LinearLayout’ within the main ‘RelativeLayout’ and place them
into this linear layout. To set their width to exactly half the width of the screen we
set the ‘gravity’ of both control to 1. We also have to set this linear layout below
the first text view.
• We repeat the above procedure for another text view and edit text. Set this linear
layout below the previous Linear layout.
• Now we add a button below the second linear layout section and set its width to
the ‘match_parent’.

Code for achieving this layout:

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop ="true"
android:text="Please enter the required information" />

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="@+id/textView1"
android:id="@+id/Section1"
>

<TextView
android:id="@+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="First Value"
/>

<EditText
android:id="@+id/et1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
</EditText>

</LinearLayout>

<LinearLayout
android:id="@+id/Section2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="@+id/Section1">

<TextView
android:id="@+id/textView3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Second Value" />

<EditText
android:id="@+id/et2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />

</LinearLayout>

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/Section2"
android:layout_centerHorizontal="true"
android:text="OK" />

The snapshot of this layout in portrait orientation:


A snapshot in landscape orientation:
Lab Task 3: (5 marks)
• Create a new activity.
• Pass the values given by user in the first activity to the second activity.
• Now in the second activity print the table of the numbers input by the user.

Procedure:
• Create a new class and a new XML layout for a second activity.
• In the new view insert an ‘EditText’ or a ‘TextView’ and set its width and height to
‘match_parent’.
• Now create a new intent in the on click code of the button created in the
previous view.
• With this intent we will pass the values input from the user in the first and second
Edit text.
• To pass the values we need to send them as extra items with the intent. For this
we will use the ‘intent.putExtra()’ method, that requires an identifying key and the
item to be sent as parameters.

The Code below shows how to do this:

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
b = (Button) findViewById(R.id. button1);

b.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
Integer temp1, temp2;
temp1 = Integer.parseInt(et1.getText().toString());
temp2 = Integer.parseInt(et2.getText().toString());
Intent i = new
Intent(MainActivity.this,SecondActivity.class);
i.putExtra("first", temp1);
i.putExtra("second", temp2);
startActivity(i);
}
});
}

• After this we need extract the extra content in the new activity. To achieve this we
can use the ‘intent.getIntExtra(key, defaultvalue)’ method which takes the key as a
parameter and any integer value as another parameter.
• After we obtain these values in the second activity we can use them to print a
table.

The code below demonstrations how to do this:

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
et1 = (EditText) findViewById(R.id.editText1);

Intent i2 = getIntent();
int temp1 = i2.getIntExtra("first", 0);
int temp2 = i2.getIntExtra("second", 1);

for(int i=1; i<=temp2; i++)


{
int temp3 = temp1 * i;
et1.append(Integer.toString(temp1)+"*"+
Integer.toString(i)+"= "+ Integer.toString(temp3)+'\n');
}
}

The snapshots on the next page shows how this app works.

Snapshot of the app in action:


Conclusion:
In this lab I learned how to add extra data to an intent and then retrieve it in the new
activity that was started. I also learned how to make a layout that can adjust properly in
both landscape and portrait mode.

You might also like