August 30, 2010

Android Basics-2 (Activity and Intents)

 

Activity is the complete thing which U see on the complete screen.It could be anything on the screen like Buttons, Edittext boxes,Texts, Radio Buttons, lists, etc… are all part of Activity.So Activity is like complete thing which is running presently on the screen.

 

Lets try with an example, I’ll explain everyline after the code along with the xml file.The Objective of this Android Project is to switch between 2 activities on click of a button.

In Eclipse, Simply create new Android project with name ‘SwitchActivity’, project name as ‘com.android.switchact’, activity with ‘SwitchingActivities’. Now override the java file in src/SwitchingActivities.java with

package com.android.switchact;

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.TextView;

public class SwitchingActivities extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView text1 = (TextView)findViewById(R.id.text1);
Button next = (Button)findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(v.getContext(),activity2.class);
startActivity(i);
}
});
}


}//end of class Swithchign activities



Now lets take the res/Layout/main.xml file,override the whole content of main.xml file with the following code


<?xml version="1.0" encoding="utf-8"?>
<TableLayout
android:id="@+id/widget47"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TableRow
android:id="@+id/widget48"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="In Activity1"
>
</TextView>
<Button
android:id="@+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="next"
>
</Button>
</TableRow>
</TableLayout>





Please look at this XML file carefully, its needed .


First lets get in to this main.XML file..


image


I’ll specify what I was thinking to make on the screen.In one Activity,I want to make table on the screen with a text specifying in which Activity the present Screen is in and a Button in that table to switch between activities, when clicked.


There are different types of layouts in Android.TableLayout, RelativeLayout, LinearLayout etc..I recommend to know about these different types of layouts. So as this is a table there must be some Rows and Columns. Interestingly there is a <TableRow> tag in XML can be utilized as a Row for TableLayout.


We can embed any number of things in this TableRow depending on the screen size.Lets take one TableRow and add one TextView element with String “Activity 1”. Then add one Button with text ”next” and I want to switch to other activity with this Button. Now, If U look closely in the XML code there are some parameters called as layout_width and layout_height for each item. We need to specify Height and Width of each element as Mobile screen is limited.I asked TableLayout to “fill_parent” in both Height and Width for which it has to fill to its boundaries, the Whole screen.Next I added one TableRow saying it to wrap(“wrap_content”) its height and fill(“fill_parent”) its width completely to the table enough to represent the elements in it, as here a TextView and a Button.If I hadn’t said to wrap the width of TextView it will occupy the whole TableRow, a row filled with only one element, then I cannot add a Button to it.Thats why I said to wrap(“wrap_content”) the width of TextView according to the size of text in it. Then I added Button in TableRow an also wrapped it as I don’t want to mess with its size.



In SwitchingActivities.java, its class extends Activity means this java file can run as an Activity and we want to do that with command


setContentView(R.layout.main);



This command will run/bring the whole User Interface or Graphics in main.xml(R.layout.main is an Id to main.xml file) on the screen of Emulator.


Here ‘R.layout.main’ specifies to load the content of main.xml in layout folder in R.java file.So, where is this R.java and what it is?? R.java is like a registry file which has all id’s of all the elements in res folder.Id’s are nothing but just integers associated to the resources like Buttons, Images, Strings, TextViews, EditTexts, XML files etc..Each resource has different Id.


In any Android Project there are 2 things, Front-end and back-end. Front-end is like complete graphics or UI of the activity which we do it in XML files(in Java also it can be done but its painstaking).Back-end is like the logic or IQ part of the application which we implement using java code.


We have XML component but we need to use it in this java code as this java code is the logic part and so we need to link our UI and logic to make application perfect. this is done by the code


Button next = (Button)findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(v.getContext(),activity2.class);
startActivity(i);
}
});

We linked java Button element with the Button in main.xml file by its ID in R.java.Implemented a onClickListener() to it.


In main.xml we have a Button with id “next” and TextView with id “text1” in this activity.When this Activity is running there will be a text specifying “In Activity 1” and a Button with text “Next” on it. But I want to run other activity when I click this ‘Next’.So, My activity should be watching this button from when it had started and when ‘next’ got pressed/clicked it has to switch over to other activity and this can be accomplished by listeners.Listeners are the things which listen and when appropriate click is done it starts  working.We have onClickListener() function for Buttons, MotionEvent for Touch etc.. Other activity is started by using intents.Intent specifies what operation must be performed.So, I used Intent to start a new Activity using code shown below.


Intent i = new Intent(v.getContext(),activity2.class);
startActivity(i);

New Activity also needs similar structure of UI, an XML file and a java Class, which must extend activity.so create new class by right-clicking on src folder and click new, name it as  ‘activity2’ .Make the following code for activity2.java.


package com.android.switchact;

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.TextView;

public class activity2 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
TextView text2 = (TextView)findViewById(R.id.text2);
Button previous = (Button)findViewById(R.id.previous);
previous.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent();
finish();
}
});
}


}



Here please don’t write the import statements. Ofcourse, U’ll get error in Eclipse as it can’t find the related functions but click on the error and it automatically displays why error occurred and will Add import statements itself.There are lot of shortcuts in Eclipse. just while typing any function type first 2 letters and hit ctrl+space  it gives the list of similar functions from its libraries.Know shortcuts and complete the work soon, Don’t type everything as Eclipse IDE can do more than half of the coding work. :)


In activity2.java there is code



setContentView(R.layout.activity2);



This loads the UI of activity2.xml, which means each activity needs an XML or UI elements to run or else there will be no display or I don’t know, it might give an error also ;)..create new Android XML file in res/layout folder, name it as “activity2.xml” . Open the activity2.xml file and override it with the following xml components..


<?xml version="1.0" encoding="utf-8"?>
<TableLayout
android:id="@+id/widget47"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TableRow
android:id="@+id/widget48"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/text2"
android:layout_width="250px"<!—-this is the way to write comment in xml -->
<!--here 250px means 250 pixels of screem -–>android:layout_height="wrap_content" android:text="In Activity2"
>
</TextView>
<Button
android:id="@+id/previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous"
>
</Button>
</TableRow>
</TableLayout>



If U take a closer look, its very much similar to the main.xml but look steeply I changed the Id’s, text and  layout parameters of TextView. If there is no change of Id’s then we get error as all these elements will be part of R.java(Registry) and as there is a duplicate item it throws error.


Now I’ll say what I wanted to do with this Activity.When I click the button in this activity, this activity should close itself and come back to previous activity. Thats why I named the button as Previous. See the TextView, its text is “In Activity 2” just to know that we are in other activity.


here command


finish();



is to shutdown this activity or else we can call other activity from this one just by using Intents.


When U run this project as Android Application U must see this screen


image


and after clicking next button U must see other activity. Check out the text displayed changes on the screen according to the click of these buttons from “in Activity 1” to “In Activity 2” and viceversa.


image


Lastly U need to know about Android Manifest file in Your Project.This is the file which specifies what activities are there in your app what permissions do they need like dial numbers, get contacts, access http, access maps,access gps etc.. This file can also include any user-libraries for custom made app of our own libraries.This file must contain list of all activities or else there will be “Force close” error on emulator.To specify that there is an activity callled as “activity2.java” change the AndroidManifest.xml according to code shown below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.switchact"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SwitchingActivities"
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=".activity2"></activity>
</application>


</manifest>



Hope U enjoyed this tutorial and got everybit of Activity. But, there is saying that if an application has too many activities application slows down accordingly,because they pile up on the stack reducing the RAM.


Now , I want U  all to know this is just basics and We should not stop at basics there are couple of things to be done by U all. Just Google these concepts to complete the tasks



1) I want to pass a String data to and from both activities using bundle(Google this one) concept.just use functions like putExtras() to achieve this task.


2) Download DroidDraw from http://www.droiddraw.org/ ,this tool is considered as the best tool to make xml file, just follow the first 2 tutorials in this site. By this U‘ll understand that its very much easy to make UI components using XML.(By this tool there is no need to type the XML file just create it graphically) :D


3) now Add other TableRow and add button to it,look out how the whole UI changes according to other TableRow. Do it in Droiddraw ;)

No comments:

Post a Comment