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 ;)

Common tasks for Android Developers

 

Google knew that its very tough to get some minimum basics for Android development. They made a list of programming skills needed for basic developers to advance in depth later. So, these programming skills must be acquired by each and every Android Developer.

 

This list is at http://developer.android.com/guide/appendix/faq/commontasks.html ..When an task on list is clicked some info on How to do that task  is given by showing some functions and some methods to complete it.

So, I will be posting all the info and code snippets to complete the task..

Android Basics –1 (LogCat)

 

When an App is run as Android Application the whole project will run on emulator as .apk file. in this apk file all the files, images, xml, java byte code will be packed. When a new Android Project is created a lot of files and folders are created.Res folder contains all the resources for Layout, Strings, images as Drawable which can be used by any part of the application. Layout folder contains all the XML files which describes the layout. String folder contains all the string resources which can be used in the app.However I want to say something which is beyond what books say.

 

Whenever there is a runtime error the app in the Emulator just closes mostly saying “Force Close”. User cannot do anything in this situation except accept the error and click on “Force Close”. This sort of error occur manytimes in development of any app and Developers starts scratching their heads to find out what could be wrong in the code. In this situation I recommend to watch out Logcat. This is the tool which displays what's happening in the Emulator and whenever there is an an Error, Logcat clearly specifies the error by telling there was a “NullPointerExcepion” while accessing a particular function or “ArrayOutOfBoundException” at a particular line etc..

image

To access logcat u have to change the perspective from java to DDMS, then look a mid portion of the screen where it looks similar to the given image below

 image

In this Logcat its easy to find any errors/ exceptions at runtime and even We can use this logcat as output rather than getting output in Emulator screen. To use logcat as output a funtion must be run in Java code and this function is

//Log.i(String tag, String message);done as following
Log.i("Hi"."Button Clicked");

Here when this line is run it displayed “Hi” under tab and “Button Clicked”  as message.


Hope U liked this basic understanding and please feel free to ask any doubts..

August 28, 2010

Requirements for Android

So, lets start what are the requirements needed for Android application development.
1) Eclipse IDE: This is the IDE where Android apps will be written and compiled in an Emulator. Emulator is the virtual android device where the application code will be made to run/executed just as it could be in a real Mobile.But, in Eclipse Android Emulator is not provided, it just compiles the code and if found any errors it give a red cross. So, we must download Emulator to run the application.Eclipse by default doesn’t know anything about Android and so Google provided some Android Libraries(along with its own Tools) which can be included into Eclipse as an Environment to execute the code.Interestingly Google provides these Android libraries as Android SDK(Software Development KIT). This kit also includes the Emulator :) All in one shot..get Eclipse Galileo/Helios any version  at www.eclipse.org/downloads/
2) Android SDK: As I said this SDK is the thing which has all the libraries needed for Android execution and also it has the Emulator to run the app as it runs in normal Android phone.Get Android SDK at the site given, http://developer.android.com/sdk/index.html. So now we have all the requirements needed Eclipse and Android SDK but as I said how does Eclipse can get all these SDK libraries in to it?? We need to link this SDK to Eclipse to start A new Android Project.
3) This linking is done in Eclipse by its plug-ins.Plug-in is the thing just as a wire with a plug. Just like when we need to run a TV first We need to plug-in the TV cable to switchboard.Same as that We need a eclipse plug-in to show new perspective of compiling environment simply call it as Android Environment.This plug-in is called Android Development Tool(ADT). After Installing Eclipse goto Help –> Install new Software and type in - Work with  “https://dl-ssl.google.com/android/eclipse/” . Next just include all tools and complete the installation!!
4) Unzip the Android SDK to any drive. Open Eclipse then window –> preferences –> Android ! Here browse the SDK location to the unzipped Android SDK folder. After this is done Eclipse loads all the libraries and must add a perspective called DDMS and also When U open new project there must be ‘New Android Project’ to select . If DDMS or ‘New Android Project’ doesn’t appear then linking Android to Eclipse failed, repeat again.
5) So after making a ‘New Android Project’ and writing all the code where can we compile, we need an Emulator and to our interest Emulator is in SDK and We had linked this SDK to Eclipse. Simple We must be able to launch an Emulator from Eclipse to run the Android Projects.click Window –> Android SDK and AVD manager, before Going in this section U need to know some details about Android.
Google bought Android company in 2002 and then they started this Android SDK version 1.0 in 2008. From here things went far beyond anyone could expect.Google started initiative of OHA(Open Handset Alliance) and manufacturers must be join this OHA to produce Android phones. Now there are more than 100 Mobile manufacturers in this OHA from Nokia, Samsung, Sony, LG, Dell, Kyocera, HTC etc…So things were like a competition, till 2009 only 2-3 Android phones(including Google nexus) were in the market but in early 2010 there was sudden splurge of Android phones and  Android SDK versions creating dilemma for Developers. From 2008 to 2010 different versions of Android SDK were released, from 1.0 –> 1.5 –> 1.6 –> 2.0 –> 2.1 –>2.2(mid of 2010)  were rolled out. The need to make such versions shows the way Android Source code evolved.So, in our SDK we will be having all these emulators from 1.0 to the latest one. Emulator is an AVD(Android Virtual Device).There are many manufacturers still developing Android Apps in SDK 1.5 and 1.6 versions like Dell with their mobile Aero.
So, when We need to compile the Android App we need an emulator and there are many versions of Emulator from 1.0 to 2.2(2.2 is the latest one). When window –> Android SDK and AVD manager is opened u’ll see this dilemma.Write a name of your choice select a Emulator version which is the latest one.For a normal developer 50 MB of SD card is more than sufficient.
Skin is the thing which differs lot. There are many Android devices in the market ranging from mobiles to tablets. When developing apps for tablets we must have a emulator which is  quite relevant and appropriate to the real Device. There skin comes to picture, tablets have high resolution compared to normal Mobiles. To make such an Emulator just click resolution and type the numbers like 800 X 600 to get the screen equivalent to such resolution tablet.For normal mobile app development just use built-in skin. click create, then we get an new AVD where we can compile the Android apps. :)

so we have all the needed things to compile Android apps and now just create new android project fill up the project name with “Hello World”, application name with “Hello Android”, package name with “com.android.hello”, sdk version to the appropriate version of AVD U just created and then Create Activity to “Hello Android”. now just right-click the project name in the left-side project explorer, wait a couple of minutes to send this project code to emulator. Then U can see “Hello World”  on the Emulator screen.Don’t get stumbled when U see different types of  files in your project.

Hope U enjoyed this post. Pls ask questions if u get any doubts!!

August 27, 2010

Welcome to Android

 

so Guys & Gals, this is my blog and I’ll be posting a lot about Android. If you are new to Android and want to be a perfect programmer for Android then pls follow this blog as I give a lot of stuff for delving inn..pls feel free to ask any doubts or any sort of questions to me at ashikch@gmail.com or just comment here and ill post appropriately..