Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Android Programming(part IV)

This document provides a comprehensive guide on user interface design in Android programming, focusing on various widgets such as Text Views, Edit Texts, Buttons, Toggle Buttons, and Radio Buttons. It describes how to create and manage these UI components both in XML layout files and programmatically in activity files. Additionally, it covers setting attributes, handling events, and the visual structure of layouts in Android applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Android Programming(part IV)

This document provides a comprehensive guide on user interface design in Android programming, focusing on various widgets such as Text Views, Edit Texts, Buttons, Toggle Buttons, and Radio Buttons. It describes how to create and manage these UI components both in XML layout files and programmatically in activity files. Additionally, it covers setting attributes, handling events, and the visual structure of layouts in Android applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Android Programming

Part-IV

VERSION 1 ANDROID PROGRAMMING

1
Part-I
User Interface Design

2
USER INTERFACE DESIGN UNIT-IV

4.1 FORM WIDGETS:


Widgets enable users to interact with an Android Studio application page.
There are various kinds of widgets, such as Buttons and Text Views.
To see all the widgets at your disposal, create a new application project called ―Widgets‖
and select "empty activity". Call your activity ―Main Activity‖.
There are two components of each Android activity: the XML (Extensible Mark-up Language)
design (the beauty) and the Java text (the brains).
On the activity_main.xml page, you can see the full widgets palette underneath the various
layout options. As you can see, there are 20 widgets available for you to use. In this guide,
we’ll discuss Text Views and Buttons, which are probably the most common widgets in
Android development.
In android, Text View is a user interface control that is used to set and display the text to the
user based on our requirements. The Text View control will act as like label control and it
won’t allow users to edit the text.
In android, we can create a Text View control in two ways either in XML layout file or create it
in Activity file programmatically.

4.1.1 Create a Text View in Layout File:


Following is the sample way to define Text View control in XML layout file in android
application.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Welcome to Tutlane"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
</LinearLayout>

3
USER INTERFACE DESIGN UNIT-IV

If you observe above code snippet, here we defined a Text View control in xml layout file to
display the text in android application.

4.1.2 Create a Text View in Activity File:


In android, we can create a Text View control programmatically in an activity file based on
our requirements.

Following is the example of creating a Text View control dynamically in an activity file.

public class Main Activity extends App Compat Activity {


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearlayout);
TextView textView = new TextView(this);
textView.setText("Welcome to Tutlane");
linearLayout.addView(textView);
}
}
4.1.3 Set the Text of Android Text View:
In android, we can set the text of Text View control either while declaring it in Layout file or
by using setText() method in Activity file.
Following is the example to set the text of Text View control while declaring it in the XML
Layout file.
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to Tutlane" />
If you observe above example we used android:text property to the set required text for
TextView control in XML Layout file.
Following is another way to set the text of text view control programmatically in activity file
using set Text() method.

4
USER INTERFACE DESIGN UNIT-IV

4.2 TEXT FIELDDS:


A text field allows the user to type text into your app. It can be either single line or multi-line.
Touching a text field places the cursor and automatically displays the keyboard.
In addition to typing, text fields allow for a variety of other activities, such as text selection
(cut, copy, paste) and data look-up via auto-completion.
You can add a text field to you layout with the Edit Text object. You should usually do so in
your XML layout with a <Edit Text> element.
Text fields can have different input types, such as number, date, password, or email
address.

Note:

 In android, Edit Text is a user interface control which is used to allow the user to enter or
modify the text. While using Edit Text control in our android applications, we need to specify
the type of data the text field can accept using the input Type attribute.

 For example, if it accept plain text, then we need to specify the input Type as “text”. In case
if Edit Text field is for password, then we need to specify the input Type as “text Password”.

 In android, Edit Text control is an extended version of Text View control with additional
features and it is used to allow users to enter input values.

 In android, we can create Edit Text control in two ways either in XML layout file or create it
in Activity file programmatically.
4.2.1 Create a Edit Text in Layout File:
Following is the sample way to define Edit Text control in XML layout file in android
application.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"
android:inputType="text"/>
</LinearLayout>

5
USER INTERFACE DESIGN UNIT-IV

If you observe above code snippet, here we defined EditText control to accept plain text by
using input Type as “text” in xml layout file.

4.2.2 Create Edit Text Control in Activity File:


In android, we can create Edit Text control programmatically in an activity file to allow users
to enter text based on our requirements.
Following is the example of creating Edit Text control dynamically in an activity file.

public class MainActivity extends AppCompatActivity {


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = (LinearLayout)
findViewById(R.id.linearlayout);
EditText et = new EditText(this);
et.setHint("Subject");
linearLayout.addView(et);
}
}

4.2.3 Set the Text of Android Edit Text:


In android, we can set the text of Edit Text control either while declaring it in Layout file or
by using set Text() method in Activity file.
Following is the example to set the text of Text View control while declaring it in XML Layout
file.

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to Tutlane" />

If you observe above example we used android:text property to the set required text for Edit
Text control in XML Layout file.
Following is another way to set the text of Edit Text control programmatically in activity file
using set Text() method.

6
USER INTERFACE DESIGN UNIT-IV

4.3 LAYOUTS:
A layout defines the visual structure for a user interface, such as the UI for an activity or app
widget.
Each layout has a set of attributes which define the visual properties of that layout.
There are few common attributes among all the layouts and there are other attributes which
are specific to that layout.
Following are common attributes and will be applied to all the layouts.

4.4 BUTTON CONTROL:


Button is a user interface control which is used to perform an action whenever the
user click or tap on it. Buttons in android will contains a text or an icon or both and perform an
action when user touches it.
Different types of buttons available are Image Button, Toggle Button, Radio Button.

4.4.1 Image Control:


In android, Image Button is a user interface control that is used to display a button with an
image and to perform an action when a user clicks or taps on it.

By default, the Image Button looks same as normal button and it performs an action when a
user clicks or touches it, but the only difference is we will add a custom image to the button
instead of text.
Following is the pictorial representation of using Image Buttons in android applications.

In android, we can add an image to the button by using <Image


Button> attribute android:src in XML layout file or by using the set Image
Resource() method.

In android, we can create Image Button control in two ways either in the XML layout file or
create it in the Activity file programmatically.

7
USER INTERFACE DESIGN UNIT-IV

4.4.2 Create Image Button in XML Layout File:


Following is the sample way to define Image Button control in XML layout file in android
application.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/add_icon" />
</LinearLayout>
If you observe above code snippet, here we defined Image Button control and we are
showing the image from drawable folder using android:src attribute in xml layout file.

4.4.3 Create Image Button Control in Activity File:


In android, we can create Image Button control programmatically in activity file based on
our requirements.
Following is the example of creating Image Button control dynamically in an activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);


ImageButton btn = new ImageButton(this);
btn.setImageResource(R.drawable.add_icon);
layout.addView(btn);
4.4.4 Android Handle Image Button Click Events:
Generally, whenever the user clicks on Image Button, the Image Button object will receives
an on-click event.
In android, we can define button click event in two ways either in XML layout file or create it
in Activity file programmatically.

8
USER INTERFACE DESIGN UNIT-IV

4.5 Toggle Button:


In android, Toggle Button is a user interface control that is used to display ON (Checked)
or OFF (Unchecked) states as a button with a light indicator.
The Toggle Button is useful for the users to change the settings between two states
either ON or OFF. We can add a Toggle Button to our application layout by using
the Toggle Button object.
Following is the pictorial representation of using Toggle Button in android applications.

By default, the android Toggle Button will be in OFF (Unchecked) state. We can change the
default state of Toggle Button by using android:checked attribute.
In case, if we want to change the state of Toggle Button to ON (Checked), then we need to
set android:checked = “true” in our XML layout file.
In android, we can create Toggle Button control in two ways either in the XML layout file or
create it in the Activity file programmatically.

4.5.1 Create Toggle Button in XML Layout File:


Following is the sample way to define Toggle Button control in XML layout file in android
application.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ToggleButton
android:id="@+id/toggle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="120dp"
android:checked="true"
android:textOff="OFF"
android:textOn="ON"/>
</RelativeLayout>
9
USER INTERFACE DESIGN UNIT-IV

If you observe above code snippet, here we defined Toggle Button control and setting
Toggle Button state ON using android:checked attribute in xml layout file.

4.5.2 Create Toggle Button Control in Activity File:


In android, we can create Toggle Button control programmatically in activity file based on
our requirements.
Following is the example of creating Toggle Button control dynamically in the activity file.

RelativeLayout layout = (RelativeLayout)findViewById(R.id.r_layout);


ToggleButton tb = new ToggleButton(this);
tb.setTextOff("OFF");
tb.setTextOn("ON");
tb.setChecked(true);
layout.addView(tb);
This is how we can define Toggle Button in XML layout file or programmatically in activity file based
on our requirements.

4.5.3 Handle Android Toggle Button Click Events:


Generally, whenever the user clicks on Toggle Button, we can detect whether Toggle Button
is in ON or OFF state and we can handle the Toggle Button click event in activity file
using set On Checked Change Listener like as shown below.

Toggle Button toggle = (Toggle Button) findViewById(R.id.togglebutton);


toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListen
er() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});
This is how we can handle Toggle Button click events in android applications based on our
requirements.

10
USER INTERFACE DESIGN UNIT-IV

4.6 Radio Button:


In android, Radio Button is a two-states button that can be either checked or unchecked and
it’s the same as Check Box control, except that it will allow only one option to select from the
group of options.

The user can press or click on the radio button to make it select. In android, Check
Box control allow users to change the state of control either Checked or Unchecked but the
radio button cannot be unchecked once it is checked.

Generally, we can use Radio Button controls in an android application to allow users to
select only one option from the set of values.

Following is the pictorial representation of using Radio Button control in android


applications.

In android, we use radio buttons with in a Radio Group to combine multiple radio buttons
into one group and it will make sure that users can select only one option from the group of
multiple options.
By default, the android Radio Button will be in OFF (Unchecked) state. We can change the
default state of Radio Button by using android:checked attribute.
In case, if we want to change the state of Radio Button to ON (Checked), then we need to
set android:checked = “true” in our XML layout file.
In android, we can create Radio Button control in two ways either in the XML layout file or
create it in the Activity file programmatically.

4.6.1 Create Radio Button in XML Layout File:


Following is the sample way to define Radio Button control using Radio Group in the XML
layout file in the android application.

11
USER INTERFACE DESIGN UNIT-IV

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"
android:checked="true"/>
</RelativeLayout>
If you observe above code snippet, here we defined Radio Button control and setting Radio
Button state ON using android:checked attribute in xml layout file.

4.6.2 Create Radio Button Control in Activity File:


In android, we can create Radio Button control programmatically in activity file based on our
requirements.
Following is the example of creating a Radio Button control dynamically in activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);


RadioButton rd = new RadioButton(this);
rd.setText("Tutlane");
rd.setChecked(true);
layout.addView(rd);
This is how we can define Radio Button in XML layout file or programmatically in activity file
based on our requirements.

4.6.3 Handle Android Radio Button Click Events:


Generally, whenever the user click on Radio Button to Select or Deselect the Radio
Button object will receives an on-click event.

In android, we can define Radio Button click event in two ways either in the XML layout file or
create it in Activity file programmatically.

12
USER INTERFACE DESIGN UNIT-IV

NOTE: TOGGLE BUTTONS:


A toggle button allows the user to change a setting between two states.
You can add a basic toggle button to your layout with the Toggle Button object.
Android 4.0 (API level 14) introduces another kind of toggle button called a switch that
provides a slider control, which you can add with a Switch object.
Switch Compat is a version of the Switch widget which runs on devices back to API 7.

4.7 Android Spinner (Dropdown List) :


In android, Spinner is a view that allows a user to select one value from the list of values. The
spinner in android will behave same as a dropdown list in other programming languages.
Generally, the android spinners will provide a quick way to select one item from the list of
values and it will show a dropdown menu with a list of all values when we click or tap on it.
By default, the android spinner will show its currently selected value and by
using Adapter we can bind the items to spinner objects.
Following is the pictorial representation of using spinner in android applications.

We can populate our Spinner control with list of choices by defining an Array Adapter in
our Activity file.
Generally, the Adapter pulls data from sources such as an array or database and converts
each item into a result view and that’s placed into the list.

4.7.1 Android Adapter:


In android, Adapter will act as an intermediate between the data sources and adapter views
such as List View, Grid view to fill the data into adapter views. The adapter will hold the data
and iterates through an items in data set and generate the views for each item in the list.
Generally, in android we have a different types of adapters available to fetch the data from
different data sources to fill the data into adapter views, those are

13
USER INTERFACE DESIGN UNIT-IV

Adapter Description

Array Adapter It will expect an Array or List as input.

Curosr Adapter It will accepts an instance of a cursor as an input.

Simple Adapter It will accept a static data defined in the resources.

Base Adapter It is a generic implementation for all three adapter types and it can
be used for List View, Grid view or Spinners based on our
requirements

Now we will see how to create spinner or drop down list in android applications.
4.7.2 Create Android Spinner in XML Layout File:
In android, we can create Spinner in XML layout file using <Spinner> element with different
attributes like as shown below.

<Spinner android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

4.7.3 Populate Android Spinner with Values:


To populate spinner with list of values, we need to specify spinner adapter, such as an Array
Adapter in activity file like as shown below.

String[] users = { "Suresh Dasari", "Trishika Dasari", "Rohini Alavala", "Praveen Kumar", "Madhav Sai
" };
Spinner spin = (Spinner) find View By Id(R.id.spinner1);
Array Adapter<String> adapter = new Array Adapter<String>(this, android.R.layout.simple_spinner_i
tem, users);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.set Adapter(adapter);

This is how we can define and bind data to Spinner control in android applications. Now we
will see complete example of using spinner control android applications.

14
USER INTERFACE DESIGN UNIT-IV
4.7.4 Android Spinner Example:
Following is the example of defining a one Spinner control, one Text View control in Relative
Layout to show the list of user details in android application.
Create a new android application using android studio and give names as Spinner Example.
In case if you are not aware of creating an app in android studio check this article Android
Hello World App.
Now open an activity_main.xml file from \res\layout path and write the code like as shown
below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="@+id/txtVw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="150dp"
android:text="Select User:"
android:textStyle="bold"
android:textSize="15dp" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/txtVw"
android:layout_toRightOf="@+id/txtVw" />
</RelativeLayout>
If you observe above code we created a one Spinner control and one Text View control in
XML Layout file.
Once we are done with the creation of layout with required controls, we need to load the
XML layout resource from our activity on Create() call back method, for that open
main activity file MainActivity.java from \java\com.tutlane.spinnerexample path and write
the code like as shown below.

15
USER INTERFACE DESIGN UNIT-IV
MainActivity.java
package com.tutlane.spinnerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListe


ner {
String[] users = { "Suresh Dasari", "Trishika Dasari", "Rohini Alavala", "Praveen Kumar", "Madhav Sai
" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spin = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spin
ner_item, users);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), "Selected User: "+users[position] ,Toast.LENGTH_SHO
RT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO - Custom Code
}
}
If you observe the above code we are calling our layout using the set Content View method in the
form of R.layout.layout_file_name in our activity file. Here our XML file name
is activity_main.xml so we used file name activity_main and binding the list of values
to Spinner control using Array Adapter.

Generally, during the launch of our activity, the onCreate() callback method will be called by the
android framework to get the required layout for an activity.

16
USER INTERFACE DESIGN UNIT-IV
Output of Android Spinner Example:
When we run the above example using an android virtual device (AVD) we will get a result
like as shown below.

If you observe above result, our spinner control is like dropdown list in other programming
languages and we are able to get the selected user details in android application.
This is how we can use Spinner control in android applications to allow users to select one
value from the list of values based on our requirements.

4.8 SPINNERS / COMBO BOXES:

Spinners provide a quick way to select one value from a set. In the default state, a spinner
shows its currently selected value. Touching the spinner displays a dropdown menu with all
other available values, from which the user can select a new one.

17
USER INTERFACE DESIGN UNIT-IV

4.9 IMAGES:
public abstract class Image extends Object implements Auto
Close able java.lang.Object

↳ android.media.Image

A single complete image buffer to use with a media source such as a Media Codec or a
Camera Device.
This class allows for efficient direct application access to the pixel data of the Image through
one or more Byte Buffers. Each buffer is encapsulated in a Plane that describes the layout of
the pixel data in that plane. Due to this direct access, and unlike the Bitmap class, Images are
not directly usable as UI resources.

4.10 MENU:
In android, Options Menu is a primary collection of menu items for an activity and it is useful to
implement actions that have a global impact on the app, such as Settings, Search, etc. In case, if we
define items for the options menu in both activity or fragment, then those items will be combine and
display in UI.

4.11 DIALOG:
A dialog is a small window that prompts the user to make a decision or enter additional information.
A dialog does not fill the screen and is normally used for modal events that require users to take an
action before they can proceed.
The Dialog class is the base class for dialogs, but you should avoid instantiating Dialog directly.
Instead, use one of the following subclasses:
Alert Dialog: A dialog that can show a title, up to three buttons, a list of selectable items, or a custom
layout.
Date Picker Dialog or Time Picker Dialog: A dialog with a pre-defined UI that allows the user to
select a date or time.

18
Part-II
Database

19
DATABASE UNIT-IV

5.1 Understanding of SQLite:


SQLite is a open source SQL database that stores data to a text file on a device. Android
comes in with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you
don't need to establish any kind of connections for it like JDBC, ODBC e.t.c

5.1.1 Database – Package: The main package is android.database.sqlite that contains the
classes to manage your own databases
5.1.2 Database – Creation: In order to create a database you just need to call this method
open Or Create Database with your database name and mode as a parameter. It returns an
instance of SQLite database which you have to receive in your own object.Its syntax is given
below
6 SQLite Database my database = open Or Create Database("your database
name",MODE_PRIVATE,null);
7 Apart from this , there are other functions available in the database package , that does this
job. They are listed below

Sr.No Method & Description

1 openDatabase(String path, SQLite Database.CursorFactory factory, int flags,


DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode.
The common flags mode could be OPEN_READWRITE OPEN_READONLY

2 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)


It is similar to the above method as it also opens the existing database but it does
not define any handler to handle the errors of databases

3 openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)


It not only opens but create the database if it not exists. This method is equivalent
to openDatabase method.

4 openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)


This method is similar to above method but it takes the File object as a path
rather then a string. It is equivalent to file.getPath()

20
DATABASE UNIT-IV

Database - Insertion

we can create table or insert data into table using execSQL method defined in SQLiteDatabase
class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password
VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the same
job but take some additional parameter is given below

Sr.No Method & Description

1 execSQL(String sql, Object[] bindArgs)


This method not only insert data , but also used to update or modify already
existing data in database using bind arguments

Database - Fetching

We can retrieve anything from database using an object of the Cursor class. We will call a method
of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We
can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve the data.
That includes

Sr.No Method & Description

1 getColumnCount()
This method return the total number of columns of the table.

2 getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the

21
column

3 getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the
column

4 getColumnNames()
This method returns the array of all the column names of the table.

5 getCount()
This method returns the total number of rows in the cursor

6 getPosition()
This method returns the current position of the cursor in the table

7 isClosed()
This method returns true if the cursor is closed and return false otherwise

Database - Helper class

For managing all the operations related to the database , an helper class has been given and is
called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its
syntax is given below

public class DBHelper extends SQLiteOpenHelper {


public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}

Example

Here is an example demonstrating the use of SQLite Database. It creates a basic contacts
applications that allows insertion, deletion and modification of contacts.
To experiment with this example, you need to run this on an actual device on which camera is
supported.

22
Steps Description

1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to get references of all the XML components and
populate the contacts on listView.

3 Create new src/DBHelper.java that will manage the database work

4 Create a new Activity as DisplayContact.java that will display the contact on the
screen

5 Modify the res/layout/activity_main to add respective XML components

6 Modify the res/layout/activity_display_contact.xml to add respective XML


components

7 Modify the res/values/string.xml to add necessary string components

8 Modify the res/menu/display_contact.xml to add necessary menu components

9 Create a new menu as res/menu/mainmenu.xml to add the insert contact option

10 Run the application and choose a running android device and install the
application on it and verify the results.

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.view.KeyEvent;
23
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity {


public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mydb = new DBHelper(this);


ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,
array_list);

obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;

Bundle dataBundle = new Bundle();


dataBundle.putInt("id", id_To_Search);

Intent intent = new Intent(getApplicationContext(),DisplayContact.class);

intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
24
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);

switch(item.getItemId()) {
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);

Intent intent = new Intent(getApplicationContext(),DisplayContact.class);


intent.putExtras(dataBundle);

startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}

public boolean onKeyDown(int keycode, KeyEvent event) {


if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}

Following is the modified content of display contact activity DisplayContact.java

package com.example.sairamkrishna.myapplication;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;

25
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DisplayContact extends Activity {


int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;

TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);

mydb = new DBHelper(this);

Bundle extras = getIntent().getExtras();


if(extras !=null) {
int Value = extras.getInt("id");

if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();

String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));


String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
26
String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));

if (!rs.isClosed()) {
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);

name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);

phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);

email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);

street.setText((CharSequence)stree);
street.setFocusable(false);
street.setClickable(false);

place.setText((CharSequence)plac);
place.setFocusable(false);
place.setClickable(false);
}
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();

if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
} else{
getMenuInflater().inflate(R.menu.menu_main menu);
}
}
return true;
27
}

public boolean onOptionsItemSelected(MenuItem item) {


super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);

phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);

email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);

street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);

place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);

return true;
case R.id.Delete_Contact:

AlertDialog.Builder builder = new AlertDialog.Builder(this);


builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
28
}
});

AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();

return true;
default:
return super.onOptionsItemSelected(item);

}
}

public void run(View view) {


Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,name.getText().toString(),
phone.getText().toString(), email.getText().toString(),
street.getText().toString(), place.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
} else{
if(mydb.insertContact(name.getText().toString(), phone.getText().toString(),
email.getText().toString(), street.getText().toString(),
place.getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}
}
}

Following is the content of Database class DBHelper.java


29
package com.example.sairamkrishna.myapplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "MyDBName.db";


public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;

public DBHelper(Context context) {


super(context, DATABASE_NAME , null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}

public boolean insertContact (String name, String phone, String email, String street,String place) {
30
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}

public Cursor getData(int id) {


SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}

public int numberOfRows(){


SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}

public boolean updateContact (Integer id, String name, String phone, String email, String
street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}

public Integer deleteContact (Integer id) {


SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}

public ArrayList<String> getAllCotacts() {


ArrayList<String> array_list = new ArrayList<String>();
31
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();

while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}

Following is the content of the res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Data Base" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<ImageView
android:layout_width="wrap_content"
32
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/logo"/>

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/scrollView"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">

<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>

</ScrollView>

</RelativeLayout>

Following is the content of the res/layout/activity_display_contact.xml

<?xml version="1.0" encoding="utf-8"?>


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DisplayContact" >

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
33
<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >
</EditText>

<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextStreet"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextName"
android:layout_alignParentLeft="true"
android:text="@string/name"
android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/save" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
34
android:layout_alignBottom="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView1"
android:text="@string/email"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextPhone"
android:layout_alignLeft="@+id/textView1"
android:text="@string/phone"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView5"
android:text="@string/street"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/editTextCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editTextName"
android:layout_below="@+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editTextCity"
android:layout_alignBottom="@+id/editTextCity"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/editTextEmail"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
35
android:id="@+id/editTextStreet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextName"
android:layout_below="@+id/editTextPhone"
android:ems="10"
android:inputType="text" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextName"
android:ems="10"
android:inputType="phone|text" />

</RelativeLayout>
</ScrollView>

Following is the content of the res/value/string.xml

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="app_name">Address Book</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Add_New">Add New</string>
<string name="edit">Edit Contact</string>
<string name="delete">Delete Contact</string>
<string name="title_activity_display_contact">DisplayContact</string>
<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="email">Email</string>
<string name="street">Street</string>
<string name="country">City/State/Zip</string>
<string name="save">Save Contact</string>
<string name="deleteContact">Are you sure, you want to delete it.</string>
<string name="yes">Yes</string>
<string name="no">No</string>
</resources>

Following is the content of the res/menu/main_menu.xml

36
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>

</menu>

Following is the content of the res/menu/display_contact.xml

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/Edit_Contact"
android:orderInCategory="100"
android:title="@string/edit"/>

<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/delete"/>

</menu>

This is the defualt AndroidManifest.xml of this project

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

37
</activity>

<activity android:name=".DisplayContact"/>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device
with your computer. To run the app from Android studio , open one of your project's activity files
and click Run icon from the tool bar. Before starting your application,Android studio will display
following window to select an option where you want to run your Android application.

38

You might also like