Android tutorial


Published on

Initial android tutorial for beginers

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Android tutorial

  1. 1. The Android platformWith Androids breadth of capabilities, it would be easy to confuse it with a desktop operatingsystem. Android is a layered environment built upon a foundation of the Linux kernel, and it includesrich functions. The UI subsystem includes:  Windows  Views  Widgets for displaying common elements such as edit boxes, lists, and drop-down listsAndroid includes an embeddable browser built upon WebKit, the same open source browser enginepowering the iPhones Mobile Safari browser.Android boasts a healthy array of connectivity options, including WiFi, Bluetooth, and wireless dataover a cellular connection (for example, GPRS, EDGE, and 3G). A popular technique in Androidapplications is to link to Google Maps to display an address directly within an application. Support forlocation-based services (such as GPS) and accelerometers is also available in the Android softwarestack, though not all Android devices are equipped with the required hardware. There is also camerasupport.Historically, two areas where mobile applications have struggled to keep pace with their desktopcounterparts are graphics/media, and data storage methods. Android addresses the graphicschallenge 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 SQLitedatabase. Figure 1 shows a simplified view of the Android software layers.Figure 1. Android software layers Back to topApplication architectureAs mentioned, Android runs atop a Linux kernel. Android applications are written in the Javaprogramming language, and they run within a virtual machine (VM). Its important to note that the VMis not a JVM as you might expect, but is the Dalvik Virtual Machine, an open source technology.
  2. 2. Each Android application runs within an instance of the Dalvik VM, which in turn resides within aLinux-kernel managed process, as shown below.Figure 2.Dalvik VMAn 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. Services A 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 providers You can think of content providers as a database server. A content providers 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 youre 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 receivers An 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 thedevice. 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 requiresaccess to the network — to download a file, for example — this permission must be explicitly statedin the manifest file. Many applications may have this specific permission enabled. Such declarativesecurity 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 andpress Next
  3. 3. Fill in the following detail i.e. Project Name, Package Name, Activity Name, Application Name and selectthe Build Target (Android SDK Version) and press “Finish”
  4. 4. Following structure tree will appear in Package Explorer window.In above structure following things are noticeable.
  5. 5.  Src o Package that will contain source code for project  Gen o Package that will contain automatic generated code like  Assets o Folder that will contain the assets of application like DB, data storage files etc.  Res o Folder that will contain all the resources like, layouts, graphics and constant values, animations etc.  AndroidManifest.xml o A Configuration file for android application.Now make a Virtual Device by clicking on the mobile icon on you eclipse IDE or select from Windowmenu “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.
  6. 6. Press Create AVD after filling in the information.
  7. 7. Select the AVD you’ve just created and Press Start.Now right click on your project and select Run As->Android Application
  8. 8. You application will appear on the EmulatorNow Open main.xml from layout folder.Select main.xml tab it will show the XML .
  9. 9. Now replace the XML code with following Code.<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns: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=""
  10. 10. 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.
  11. 11. Now Add the Following Code in start of class//Private Controls EditTexttxtFname,txtLastName,txtId,txtCourse; Button btnSubmit,btnClear;Add the following code after setContentView(R.layout.main);//Getting layouts ControlstxtFname=(EditText)findViewById(;txtLastName=(EditText)findViewById(;txtId=(EditText)findViewById(;txtCourse=(EditText)findViewById(;btnSubmit=(Button)findViewById(;btnClear=(Button)findViewById(;Now implement the OnClickListener Interface but addImplements OnClickListener to Class definition i.e.publicclassMainActivityextends Activity implementsOnClickListenerNow Implement the OnClick Method of OnClickListener Interface@Override publicvoidonClick(View v) { // TODO Auto-generated method stub }Add the following code for Button Clicks in onClick Methodswitch(v.getId()) { case break; case //Clear Controls this.txtFname.setText(""); this.txtLastName.setText(""); this.txtId.setText(""); this.txtCourse.setText(""); break; }Now Register Buttons with Click Handler
  12. 12. //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.
  13. 13. Click “Finish” after entering File nameNow 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=""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>
  14. 14. <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>
  15. 15. 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 onClickMethod should look like this@Override publicvoidonClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case //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 this.txtFname.setText(""); this.txtLastName.setText(""); this.txtId.setText(""); this.txtCourse.setText(""); break; } }Add the Following code in StudentDetail ClassTextViewlblFname, lblLastName,lblID,lblCourse; Button btnBack; @Override protectedvoidonCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //Setting the Layout setContentView(R.layout.studentdetail); lblFname=(TextView)findViewById(; lblLastName=(TextView)findViewById(; lblID=(TextView)findViewById(; lblCourse=(TextView)findViewById(; btnBack=(Button)findViewById(; //Setting on Click of Back Button btnBack.setOnClickListener(this); //Getting Student Detail from Intent and populating the controls Bundle extras=getIntent().getExtras();
  16. 16. lblFname.setText(extras.getString("FName")); lblLastName.setText(extras.getString("LName")); lblID.setText(extras.getString("Id")); lblCourse.setText(extras.getString("Course")); } @Override publicvoidonClick(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> TagNow Run you Application.Using Database in Android ApplicationsNow 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 withgeneral SQL and is generally use with mobile platforms .Add a new class to your source package name it asDBHelperAdd 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
  17. 17. 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 InsertionpublicvoidinsertDate(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 firstDBHandlerobjDB;Now initialize this object in OnCreate MethodobjDB=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());
  18. 18. 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().toString(),txtCourse.getText().toString(), txtId.getText().toString()); startActivity(i);Run your Application now on Submit button click it will save the record inthe database and show the current record on next screen.Now Add Code to Fetch Record in DBHandler classpublic Cursor fetchTableData(String sql) { returndb.rawQuery(sql,null); }This method will fetch the data into a cursorNow we will have to write a method to store retrieved data into a list so wecan 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.xmlAdd 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=""><ListViewandroid:id="@+id/listStudent"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout>
  19. 19. 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 eachcell of ListView given in above design.Name this new XML file as student_row.xml and paste the following code intoit.<?xmlversion="1.0"encoding="UTF-8"?><TextViewandroid:id="@+id/text1"xmlns: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 StudentsListViewlistStudents;//DB ObjectDBHandlerobjDB;Now paste the following code in the OnCreate Method.//initialization of DB ObjectobjDB=newDBHandler(this); //Set Design of Activity setContentView(R.layout.student_list); //Controls to be populated in List int[] to = newint[]{}; //List of student which will be populated as a result of fetchoperation on DB ListstdList=newArrayList<String>(); //List Population stdList=objDB.getData(); //Get Reference of the ListView from the Design listStudent=(ListView)findViewById(;
  20. 20. //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 intoHash 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 , CellLayout 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 inStudent Detail Activity.Intent i=newIntent(this,StudentList.class); startActivity(i);Now Run your Application.