SlideShare a Scribd company logo
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.
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.
  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 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 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 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 Project
Go to File Menu and select New Project. Following dialog box will appear select Android Project and
press Next
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”
Following structure tree will appear in Package Explorer window.




In above structure following things are noticeable.
   Src
            o    Package that will contain source code for project
       Gen
            o    Package that will contain automatic generated code like R.java
       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 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.
Press Create AVD after filling in the information.
Select the AVD you’ve just created and Press Start.




Now right click on your project and select Run As->Android Application
You application will appear on the Emulator




Now Open main.xml from layout folder.




Select main.xml tab it will show the XML .
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"
>
<TextView
android: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=""
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.
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 layout's Controls
txtFname=(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

@Override
      publicvoidonClick(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 Controls
                     this.txtFname.setText("");
                     this.txtLastName.setText("");
                     this.txtId.setText("");
                     this.txtCourse.setText("");
                     break;
               }


Now Register Buttons with Click Handler
//Setting Button Clicks
btnClear.setOnClickListener(this);
btnSubmit.setOnClickListener(this);




Now Add a New Layout by right clicking on Layout folder and select New->File
following dialog will appear.
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>
<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>
<Button
android:text="Back "
android:id="@+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
/>


</LinearLayout>
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

@Override
      publicvoidonClick(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;

       @Override
       protectedvoidonCreate(Bundle savedInstanceState) {
             // TODO Auto-generated method stub
             super.onCreate(savedInstanceState);
             //Setting the Layout
             setContentView(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 Button
               btnBack.setOnClickListener(this);

               //Getting Student Detail from Intent and populating the controls
               Bundle extras=getIntent().getExtras();
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> 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 Object
SQLiteDatabasedb;
//Create Table Statement
final String CREATE_TABLE_STUDENT =
      "CREATE TABLE tbl_student ("
      + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
      + "f_nameTEXT,l_nameTEXT,courseTEXT,std_id TEXT);";


      //one argument Constructor
publicDBHandler(Context mContext){
            ctx=mContext;
      }

Now Add Following Function to Create new Database
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,nu
ll);
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());
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"?>
<LinearLayout
android: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>
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 Activity
                 setContentView(R.layout.student_list);

                 //Controls to be populated in List
                 int[] 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 Design
                 listStudent=(ListView)findViewById(R.id.listStudent);
//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.
Ad

More Related Content

What's hot (19)

What Is BuildContext In Flutter And It's Importance
What Is BuildContext In Flutter And It's ImportanceWhat Is BuildContext In Flutter And It's Importance
What Is BuildContext In Flutter And It's Importance
Andolasoft Inc
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
bantyder
 
AndroidManifest
AndroidManifestAndroidManifest
AndroidManifest
Ahsanul Karim
 
Android Applications Development
Android Applications DevelopmentAndroid Applications Development
Android Applications Development
Michael Angelo Rivera
 
Day1 before getting_started
Day1 before getting_startedDay1 before getting_started
Day1 before getting_started
Ahsanul Karim
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
amaankhan
 
Multiple Activity and Navigation Primer
Multiple Activity and Navigation PrimerMultiple Activity and Navigation Primer
Multiple Activity and Navigation Primer
Ahsanul Karim
 
Introduction to Android Development: Before Getting Started
Introduction to Android Development: Before Getting StartedIntroduction to Android Development: Before Getting Started
Introduction to Android Development: Before Getting Started
Ahsanul Karim
 
15 android libraries for app development
15 android libraries for app development15 android libraries for app development
15 android libraries for app development
Concetto Labs
 
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
Sittiphol Phanvilai
 
Training android
Training androidTraining android
Training android
University of Technology
 
Android Development Training
Android Development TrainingAndroid Development Training
Android Development Training
chandutata
 
Day 1 Android: Before Getting Started
Day 1 Android: Before Getting StartedDay 1 Android: Before Getting Started
Day 1 Android: Before Getting Started
Ahsanul Karim
 
Jaipur Bus Finder - An Android-based Application
Jaipur Bus Finder - An Android-based ApplicationJaipur Bus Finder - An Android-based Application
Jaipur Bus Finder - An Android-based Application
AI Publications
 
Google Android
Google AndroidGoogle Android
Google Android
Michael Angelo Rivera
 
Day 2 android internals a quick overview
Day 2 android internals a quick overviewDay 2 android internals a quick overview
Day 2 android internals a quick overview
Ahsanul Karim
 
Android interview questions
Android interview questionsAndroid interview questions
Android interview questions
pasalasuneelkumar
 
Android Workshop Day 1 Part 2
Android Workshop Day 1 Part 2Android Workshop Day 1 Part 2
Android Workshop Day 1 Part 2
Ahsanul Karim
 
Android developer interview questions with answers pdf
Android developer interview questions with answers pdfAndroid developer interview questions with answers pdf
Android developer interview questions with answers pdf
azlist247
 
What Is BuildContext In Flutter And It's Importance
What Is BuildContext In Flutter And It's ImportanceWhat Is BuildContext In Flutter And It's Importance
What Is BuildContext In Flutter And It's Importance
Andolasoft Inc
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
bantyder
 
Day1 before getting_started
Day1 before getting_startedDay1 before getting_started
Day1 before getting_started
Ahsanul Karim
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
amaankhan
 
Multiple Activity and Navigation Primer
Multiple Activity and Navigation PrimerMultiple Activity and Navigation Primer
Multiple Activity and Navigation Primer
Ahsanul Karim
 
Introduction to Android Development: Before Getting Started
Introduction to Android Development: Before Getting StartedIntroduction to Android Development: Before Getting Started
Introduction to Android Development: Before Getting Started
Ahsanul Karim
 
15 android libraries for app development
15 android libraries for app development15 android libraries for app development
15 android libraries for app development
Concetto Labs
 
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
Sittiphol Phanvilai
 
Android Development Training
Android Development TrainingAndroid Development Training
Android Development Training
chandutata
 
Day 1 Android: Before Getting Started
Day 1 Android: Before Getting StartedDay 1 Android: Before Getting Started
Day 1 Android: Before Getting Started
Ahsanul Karim
 
Jaipur Bus Finder - An Android-based Application
Jaipur Bus Finder - An Android-based ApplicationJaipur Bus Finder - An Android-based Application
Jaipur Bus Finder - An Android-based Application
AI Publications
 
Day 2 android internals a quick overview
Day 2 android internals a quick overviewDay 2 android internals a quick overview
Day 2 android internals a quick overview
Ahsanul Karim
 
Android Workshop Day 1 Part 2
Android Workshop Day 1 Part 2Android Workshop Day 1 Part 2
Android Workshop Day 1 Part 2
Ahsanul Karim
 
Android developer interview questions with answers pdf
Android developer interview questions with answers pdfAndroid developer interview questions with answers pdf
Android developer interview questions with answers pdf
azlist247
 

Similar to Android tutorial (20)

Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answers
kavinilavuG
 
Getting started with android dev and test perspective
Getting started with android   dev and test perspectiveGetting started with android   dev and test perspective
Getting started with android dev and test perspective
Gunjan Kumar
 
Android Basic
Android BasicAndroid Basic
Android Basic
Nirav Ranpara
 
Android
Android Android
Android
Nirav Ranpara
 
PPT Companion to Android
PPT Companion to AndroidPPT Companion to Android
PPT Companion to Android
Dharani Kumar Madduri
 
Android studio
Android studioAndroid studio
Android studio
Andri Yabu
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_android
Denis Minja
 
Technology and Android.pptx
Technology and Android.pptxTechnology and Android.pptx
Technology and Android.pptx
muthulakshmi cse
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studio
Parinita03
 
Intro to Android Programming
Intro to Android ProgrammingIntro to Android Programming
Intro to Android Programming
Peter van der Linden
 
Android Basic- CMC
Android Basic- CMCAndroid Basic- CMC
Android Basic- CMC
Pragati Singh
 
Android Tutorial
Android TutorialAndroid Tutorial
Android Tutorial
Fun2Do Labs
 
Android Intro
Android IntroAndroid Intro
Android Intro
Justin Grammens
 
Android Minnebar
Android MinnebarAndroid Minnebar
Android Minnebar
Justin Grammens
 
Part 2 android application development 101
Part 2 android application development 101Part 2 android application development 101
Part 2 android application development 101
Michael Angelo Rivera
 
android training_material ravy ramio
android training_material ravy ramioandroid training_material ravy ramio
android training_material ravy ramio
slesulvy
 
Android
AndroidAndroid
Android
San Bunna
 
Android deep dive
Android deep diveAndroid deep dive
Android deep dive
AnuSahniNCI
 
Android presentation
Android presentationAndroid presentation
Android presentation
Imam Raza
 
Android Tutorial For Beginners Part-1
Android Tutorial For Beginners Part-1Android Tutorial For Beginners Part-1
Android Tutorial For Beginners Part-1
Amit Saxena
 
Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answers
kavinilavuG
 
Getting started with android dev and test perspective
Getting started with android   dev and test perspectiveGetting started with android   dev and test perspective
Getting started with android dev and test perspective
Gunjan Kumar
 
Android studio
Android studioAndroid studio
Android studio
Andri Yabu
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_android
Denis Minja
 
Technology and Android.pptx
Technology and Android.pptxTechnology and Android.pptx
Technology and Android.pptx
muthulakshmi cse
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studio
Parinita03
 
Android Tutorial
Android TutorialAndroid Tutorial
Android Tutorial
Fun2Do Labs
 
Part 2 android application development 101
Part 2 android application development 101Part 2 android application development 101
Part 2 android application development 101
Michael Angelo Rivera
 
android training_material ravy ramio
android training_material ravy ramioandroid training_material ravy ramio
android training_material ravy ramio
slesulvy
 
Android deep dive
Android deep diveAndroid deep dive
Android deep dive
AnuSahniNCI
 
Android presentation
Android presentationAndroid presentation
Android presentation
Imam Raza
 
Android Tutorial For Beginners Part-1
Android Tutorial For Beginners Part-1Android Tutorial For Beginners Part-1
Android Tutorial For Beginners Part-1
Amit Saxena
 
Ad

Recently uploaded (20)

TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Ad

Android tutorial

  • 1. 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.
  • 2. 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. 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 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 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 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 Project Go to File Menu and select New Project. Following dialog box will appear select Android Project and press Next
  • 3. 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”
  • 4. Following structure tree will appear in Package Explorer window. In above structure following things are noticeable.
  • 5. Src o Package that will contain source code for project  Gen o Package that will contain automatic generated code like R.java  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 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.
  • 6. Press Create AVD after filling in the information.
  • 7. Select the AVD you’ve just created and Press Start. Now right click on your project and select Run As->Android Application
  • 8. You application will appear on the Emulator Now Open main.xml from layout folder. Select main.xml tab it will show the XML .
  • 9. 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" > <TextView android: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. 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. 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 layout's Controls txtFname=(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 @Override publicvoidonClick(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 Controls this.txtFname.setText(""); this.txtLastName.setText(""); this.txtId.setText(""); this.txtCourse.setText(""); break; } Now Register Buttons with Click Handler
  • 12. //Setting Button Clicks btnClear.setOnClickListener(this); btnSubmit.setOnClickListener(this); Now Add a New Layout by right clicking on Layout folder and select New->File following dialog will appear.
  • 13. 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>
  • 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> <Button android:text="Back " android:id="@+id/btnBack" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dip" /> </LinearLayout>
  • 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 onClick Method should look like this @Override publicvoidonClick(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; @Override protectedvoidonCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //Setting the Layout setContentView(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 Button btnBack.setOnClickListener(this); //Getting Student Detail from Intent and populating the controls Bundle extras=getIntent().getExtras();
  • 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> 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 Object SQLiteDatabasedb; //Create Table Statement final String CREATE_TABLE_STUDENT = "CREATE TABLE tbl_student (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "f_nameTEXT,l_nameTEXT,courseTEXT,std_id TEXT);"; //one argument Constructor publicDBHandler(Context mContext){ ctx=mContext; } Now Add Following Function to Create new Database
  • 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,nu ll); 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());
  • 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().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"?> <LinearLayout android: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>
  • 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 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 Activity setContentView(R.layout.student_list); //Controls to be populated in List int[] 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 Design listStudent=(ListView)findViewById(R.id.listStudent);
  • 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 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.