20
The Android platform With Android's breadth of capabilities, it would be easy to confuse it with a desktop operating system. Android is a layered environment built upon a foundation of the Linux kernel, and it includes rich functions. The UI subsystem includes: Windows Views Widgets for displaying common elements such as edit boxes, lists, and drop-down lists Android includes an embeddable browser built upon WebKit, the same open source browser engine powering the iPhone's Mobile Safari browser. Android boasts a healthy array of connectivity options, including WiFi, Bluetooth, and wireless data over a cellular connection (for example, GPRS, EDGE, and 3G). A popular technique in Android applications is to link to Google Maps to display an address directly within an application. Support for location-based services (such as GPS) and accelerometers is also available in the Android software stack, though not all Android devices are equipped with the required hardware. There is also camera support. Historically, two areas where mobile applications have struggled to keep pace with their desktop counterparts are graphics/media, and data storage methods. Android addresses the graphics challenge with built-in support for 2-D and 3-D graphics, including the OpenGL library. The data- storage burden is eased because the Android platform includes the popular open source SQLite database. Figure 1 shows a simplified view of the Android software layers. Figure 1. Android software layers Back to top Application architecture As mentioned, Android runs atop a Linux kernel. Android applications are written in the Java programming language, and they run within a virtual machine (VM). It's important to note that the VM is not a JVM as you might expect, but is the Dalvik Virtual Machine, an open source technology.

Android tutorial

Embed Size (px)

DESCRIPTION

Initial android tutorial for beginers

Citation preview

Page 1: Android tutorial

The Android platformWith Android's breadth of capabilities, it would be easy to confuse it with a desktop operating system. Android is a layered environment built upon a foundation of the Linux kernel, and it includes rich functions. The UI subsystem includes:

Windows Views Widgets for displaying common elements such as edit boxes, lists, and drop-down lists

Android includes an embeddable browser built upon WebKit, the same open source browser engine powering the iPhone's Mobile Safari browser.Android boasts a healthy array of connectivity options, including WiFi, Bluetooth, and wireless data over a cellular connection (for example, GPRS, EDGE, and 3G). A popular technique in Android applications is to link to Google Maps to display an address directly within an application. Support for location-based services (such as GPS) and accelerometers is also available in the Android software stack, though not all Android devices are equipped with the required hardware. There is also camera support.Historically, two areas where mobile applications have struggled to keep pace with their desktop counterparts are graphics/media, and data storage methods. Android addresses the graphics challenge with built-in support for 2-D and 3-D graphics, including the OpenGL library. The data-storage burden is eased because the Android platform includes the popular open source SQLite database. Figure 1 shows a simplified view of the Android software layers.

Figure 1. Android software layers

Back to top

Application architectureAs mentioned, Android runs atop a Linux kernel. Android applications are written in the Java programming language, and they run within a virtual machine (VM). It's important to note that the VM is not a JVM as you might expect, but is the Dalvik Virtual Machine, an open source technology.

Page 2: Android tutorial

Each Android application runs within an instance of the Dalvik VM, which in turn resides within a Linux-kernel managed process, as shown below.

Figure 2.Dalvik VM

An Android application consists of one or more of the following classifications:Activities

An application that has a visible UI is implemented with an activity. When a user selects an application from the home screen or application launcher, an activity is started.

ServicesA service should be used for any application that needs to persist for a long time, such as a network monitor or update-checking application.

Content providersYou can think of content providers as a database server. A content provider's job is to manage access to persisted data, such as a SQLite database. If your application is very simple, you might not necessarily create a content provider. If you're building a larger application, or one that makes data available to multiple activities or applications, a content provider is the means of accessing your data.

Intent/Broadcast receiversAn Android application may be launched to process an element of data or respond to an event, such as the receipt of a text message.

An Android application, along with a file called AndroidManifest.xml, is deployed to a device. AndroidManifest.xml contains the necessary configuration information to properly install it to the device. It includes the required class names and types of events the application is able to process, and the required permissions the application needs to run. For example, if an application requires access to the network — to download a file, for example — this permission must be explicitly stated in the manifest file. Many applications may have this specific permission enabled. Such declarative security helps reduce the likelihood that a rogue application can cause damage on your device.

First Android ProjectGo to File Menu and select New Project. Following dialog box will appear select Android Project and press Next

Page 3: Android tutorial

Fill in the following detail i.e. Project Name, Package Name, Activity Name, Application Name and select the Build Target (Android SDK Version) and press “Finish”

Page 4: Android tutorial

Following structure tree will appear in Package Explorer window.

In above structure following things are noticeable.

Page 5: Android tutorial

Srco Package that will contain source code for project

Geno Package that will contain automatic generated code like R.java

Assetso Folder that will contain the assets of application like DB, data storage files etc.

Reso Folder that will contain all the resources like, layouts, graphics and constant values,

animations etc.

AndroidManifest.xmlo A Configuration file for android application.

Now make a Virtual Device by clicking on the mobile icon on you eclipse IDE or select from Window menu “Android SDK and AVD Manager” a Dialog box like below will appear. Press New.

Create new AVD dialog will appear fill in the fields like given in the image.

Page 6: Android tutorial

Press Create AVD after filling in the information.

Page 7: Android tutorial

Select the AVD you’ve just created and Press Start.

Now right click on your project and select Run As->Android Application

Page 8: Android tutorial

You application will appear on the Emulator

Now Open main.xml from layout folder.

Select main.xml tab it will show the XML .

Page 9: Android tutorial

Now replace the XML code with following Code.

<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Student System"/>

<TextViewandroid:text="First Name: "android:id="@+id/TextView01"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dip"/><EditTextandroid:text=""android:id="@+id/txtFName"android:layout_width="200dip"android:layout_height="wrap_content"android:layout_marginLeft="10dip"/><TextViewandroid:text="Last Name: "android:id="@+id/TextView01"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dip"/><EditTextandroid:text=""

Page 10: Android tutorial

android:id="@+id/txtLastName"android:layout_width="200dip"android:layout_height="wrap_content"android:layout_marginLeft="10dip"/><TextViewandroid:text="Student ID: "android:id="@+id/TextView01"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dip"/><EditTextandroid:text=""android:id="@+id/txtId"android:layout_width="200dip"android:layout_height="wrap_content"android:layout_marginLeft="10dip"/><TextViewandroid:text="Course:"android:id="@+id/TextView01"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dip"/><EditTextandroid:text=""android:id="@+id/txtCourse"android:layout_width="200dip"android:layout_height="wrap_content"android:layout_marginLeft="10dip"/><Buttonandroid:text="Submit"android:id="@+id/btn1"android:layout_width="75dip"android:layout_height="wrap_content"/>

<Buttonandroid:text="Clear"android:id="@+id/btn2"android:layout_width="75dip"android:layout_height="wrap_content"/></LinearLayout>

Now select the Layout tab, following design will appear.

Page 11: Android tutorial

Now Add the Following Code in start of class

//Private ControlsEditTexttxtFname,txtLastName,txtId,txtCourse;Button btnSubmit,btnClear;

Add the following code after setContentView(R.layout.main);

//Getting layout's ControlstxtFname=(EditText)findViewById(R.id.txtFName);txtLastName=(EditText)findViewById(R.id.txtLastName);txtId=(EditText)findViewById(R.id.txtId);txtCourse=(EditText)findViewById(R.id.txtCourse);btnSubmit=(Button)findViewById(R.id.btn1);btnClear=(Button)findViewById(R.id.btn2);

Now implement the OnClickListener Interface but add

Implements OnClickListener to Class definition i.e.

publicclassMainActivityextends Activity implementsOnClickListener

Now Implement the OnClick Method of OnClickListener Interface

@OverridepublicvoidonClick(View v) {

// TODO Auto-generated method stub

}

Add the following code for Button Clicks in onClick Method

switch(v.getId()){case R.id.btn1:

break;case R.id.btn2:

//Clear Controlsthis.txtFname.setText("");this.txtLastName.setText("");this.txtId.setText("");this.txtCourse.setText("");break;

}

Now Register Buttons with Click Handler

Page 12: Android tutorial

//Setting Button ClicksbtnClear.setOnClickListener(this);btnSubmit.setOnClickListener(this);

Now Add a New Layout by right clicking on Layout folder and select New->Filefollowing dialog will appear.

Page 13: Android tutorial

Click “Finish” after entering File name

Now open the XML and Add following Code

<?xmlversion="1.0"encoding="UTF-8"?><LinearLayoutandroid:id="@+id/LinearLayout01"android:layout_width="fill_parent"android:layout_height="fill_parent"xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical">

<LinearLayoutandroid:id="@+id/LinearLayout01"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_marginTop="20dip">

<TextViewandroid:text="FName: "android:id="@+id/TextView01"android:layout_width="wrap_content"android:layout_height="wrap_content"/>

<TextViewandroid:text="Name"android:id="@+id/lblName"android:layout_width="wrap_content"android:layout_height="wrap_content"/>

</LinearLayout>

Page 14: Android tutorial

<LinearLayoutandroid:id="@+id/LinearLayout01"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_marginTop="20dip">

<TextViewandroid:text="LastName: "android:id="@+id/TextView07"android:layout_width="wrap_content"

android:layout_height="wrap_content"/><TextViewandroid:text="Last Name"android:id="@+id/lblLName"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout>

<LinearLayoutandroid:id="@+id/LinearLayout01"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_marginTop="20dip"><TextViewandroid:text="Student Id: "android:id="@+id/TextView05"android:layout_width="wrap_content"android:layout_height="wrap_content"/><TextViewandroid:text="Student ID"android:id="@+id/lblId"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout>

<LinearLayoutandroid:id="@+id/LinearLayout01"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_marginTop="20dip"><TextViewandroid:text="Course: "android:id="@+id/TextView03"android:layout_width="wrap_content"android:layout_height="wrap_content"/><TextViewandroid:text="Course"android:id="@+id/lblCourse"android:layout_width="wrap_content"android:layout_height="wrap_content"/>

</LinearLayout><Buttonandroid:text="Back "android:id="@+id/btnBack"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="20dip"/>

</LinearLayout>

Page 15: Android tutorial

Now Add a New class in Source Package and name it as StudentDetail. Extend it from Activity.

Add Following Code to OnClick method of MainActivity in first Case of switch statement now you onClick Method should look like this

@OverridepublicvoidonClick(View v) {

// TODO Auto-generated method stub

switch(v.getId()){case R.id.btn1:

//Code to submit data to next activity Intent i=newIntent(this,StudentDetail.class);i.putExtra("FName", txtFname.getText().toString());i.putExtra("LName", txtLastName.getText().toString());i.putExtra("Id", txtId.getText().toString());i.putExtra("Course",txtCourse.getText().toString());startActivity(i);

break;case R.id.btn2:

this.txtFname.setText("");this.txtLastName.setText("");this.txtId.setText("");this.txtCourse.setText("");break;

}}

Add the Following code in StudentDetail Class

TextViewlblFname, lblLastName,lblID,lblCourse;Button btnBack;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);//Setting the LayoutsetContentView(R.layout.studentdetail);

lblFname=(TextView)findViewById(R.id.lblName);lblLastName=(TextView)findViewById(R.id.lblLName);lblID=(TextView)findViewById(R.id.lblId);lblCourse=(TextView)findViewById(R.id.lblCourse);btnBack=(Button)findViewById(R.id.btnBack);

//Setting on Click of Back ButtonbtnBack.setOnClickListener(this);

//Getting Student Detail from Intent and populating the controlsBundle extras=getIntent().getExtras();

Page 16: Android tutorial

lblFname.setText(extras.getString("FName"));lblLastName.setText(extras.getString("LName"));lblID.setText(extras.getString("Id"));lblCourse.setText(extras.getString("Course"));

}

@OverridepublicvoidonClick(View v) {

// TODO Auto-generated method stub

this.finish();

}

Now Add you NewActivity(StudentDetail) in the AndroidManifest File

<activityandroid:name=".StudentDetail"android:label="Student Detail"/>

Add above line in AndroidManifest file right below the </Activity> Tag

Now Run you Application.

Using Database in Android Applications

Now we will extend our previous project to a database driven application.

Android Uses SQLite as Database Engine for its Application it is an embeded library that works with general SQL and is generally use with mobile platforms .

Add a new class to your source package name it asDBHelper

Add a Constructor with one parameter Context.

Context ctx;//Database ObjectSQLiteDatabasedb;//Create Table Statementfinal String CREATE_TABLE_STUDENT =

"CREATE TABLE tbl_student ("+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"+ "f_nameTEXT,l_nameTEXT,courseTEXT,std_id TEXT);";

//one argument ConstructorpublicDBHandler(Context mContext){

ctx=mContext;}

Now Add Following Function to Create new Database

Page 17: Android tutorial

privatevoidcreateOpenDB(){

try{db = ctx.openOrCreateDatabase( "StudentData.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );

db.setVersion(1);db.setLocale(Locale.getDefault());db.setLockingEnabled(true);

db.execSQL(CREATE_TABLE_STUDENT);}catch(Exception ex){

db=ctx.openOrCreateDatabase("StudentData.db",SQLiteDatabase.OPEN_READWRITE,null);db.setVersion(2);db.setLocale(Locale.getDefault());db.setLockingEnabled(true);

}

}

Add Code of Record Insertion

publicvoidinsertDate(String fName,StringlName,String course, String stdId){createDB();ContentValues values = newContentValues();

values.put("f_name", fName);values.put("l_name",lName);values.put("course", course);values.put("std_id",stdId);db.insert("tbl_student", null, values);Toast.makeText(ctx, "Record Saved",Toast.LENGTH_LONG).show();

}

Add an object of DBHandler Class in Main Activity first

DBHandlerobjDB;

Now initialize this object in OnCreate Method

objDB=new DBHandler(this);

Now Add the Code to insert record

//Code to submit data to next activity Intent i=newIntent(this,StudentDetail.class);i.putExtra("FName", txtFname.getText().toString());

Page 18: Android tutorial

i.putExtra("LName", txtLastName.getText().toString());i.putExtra("Id", txtId.getText().toString());i.putExtra("Course",txtCourse.getText().toString());

//objDB.insertDate(txtFname.getText().toString(),txtLastName.getText().to

String(),txtCourse.getText().toString(), txtId.getText().toString());startActivity(i);

Run your Application now on Submit button click it will save the record in the database and show the current record on next screen.

Now Add Code to Fetch Record in DBHandler class

public Cursor fetchTableData(String sql) {

returndb.rawQuery(sql,null);

}

This method will fetch the data into a cursor

Now we will have to write a method to store retrieved data into a list so we can use it on other places.

publicArrayList<String>getData(){createDB();ArrayListstudentList=newArrayList<String>();Cursor cur =fetchTableData("select * from tbl_student");

cur.moveToFirst();while (cur.isAfterLast() == false) {studentList.add(cur.getString(1));

cur.moveToNext(); }cur.close();

returnstudentList; }

Now Add a New XML in layout folder name it as student_list.xml

Add following code in this newly created xml file.

<?xmlversion="1.0"encoding="UTF-8"?><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"xmlns:android="http://schemas.android.com/apk/res/android"><ListViewandroid:id="@+id/listStudent"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout>

Page 19: Android tutorial

Above design contains a ListView which will show a list in your Activity.

Now Create another XML file in layout folder as which will represent each cell of ListView given in above design.

Name this new XML file as student_row.xml and paste the following code into it.

<?xmlversion="1.0"encoding="UTF-8"?><TextViewandroid:id="@+id/text1"xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="15dip"/>

Now Add another class named StudentList.Java in you source package.

Extend it from Activity to make it an Activity. Implement OnCreate Method.

Define private controls and objects

//List of Students

ListViewlistStudents;

//DB Object

DBHandlerobjDB;

Now paste the following code in the OnCreate Method.

//initialization of DB Object

objDB=newDBHandler(this);

//Set Design of ActivitysetContentView(R.layout.student_list);

//Controls to be populated in Listint[] to = newint[]{R.id.text1};

//List of student which will be populated as a result of fetch operation on DB

ListstdList=newArrayList<String>();

//List Population stdList=objDB.getData();

//Get Reference of the ListView from the DesignlistStudent=(ListView)findViewById(R.id.listStudent);

Page 20: Android tutorial

//Prepare a list of Key Value Pair Hash to populate the ListView

List<Map<String,Object>> list=newArrayList< Map<String,Object>>(stdList.size());

//For loop to get each instance from student list and put it into Hash list which will be used to populate ListView

for(int i=0; i<stdList.size(); i++){Map<String,Object> map = newHashMap<String,Object>();map.put("Name", stdList.get(i));list.add(map);

}

//Set adapter to the ListView with control to be populated , Cell Layout and list of data

listStudent.setAdapter(newSimpleAdapter(this,list,R.layout.student_row,new String[] { "Name"}, to));

Now Add this Activity to your AndroidManifest.xml file.

Add Code to start this activity in the OnClick Method for Back Button in Student Detail Activity.

Intent i=newIntent(this,StudentList.class);startActivity(i);

Now Run your Application.