SlideShare a Scribd company logo
1 of 122
Android Developer
m a r t e s , 7 d e e n e r o d e 2 0 1 4
Connect DB SQLite to Android With Android Studio
Connect DB SQLite to Android With Android Studio
CREATE FAST APPS HERE
DOWNLOAD ALL THE PROYECT HERE
One of the first and more important information are: How to connect SQLite with Android app?
For this tutorial I am using Android Studio. You can download this from HERE
First we need to create we database. I am using SQLite Manager (this is a plugin for Firefox).
I create a Data Base named "example" and a table named "exampleTable".
CREATE TABLE exampleTable ( name VARCHAR(200) NULL DEFAULT NULL, lastname
VARCHAR(200) NULL DEFAULT NULL, ID VARCHAR(20) NULL DEFAULT NULL )
INSERT INTO exampleTable VALUES('Jhon', 'Sweet', '1');
INSERT INTO exampleTable VALUES('Audrey', 'Owen', '2');
INSERT INTO exampleTable VALUES('Michelle', 'Peters', '3');
INSERT INTO exampleTable VALUES('Helen', 'Black', '4');
INSERT INTO exampleTable VALUES('Jessica', 'Sweet', '5');
When the database are create, we need to put in the assent folder, in the Android Studio Proyect.
Then we create a Connection class.
In this class are two important lines in this class:
private static String DB_PATH = "/data/data/com.example.databaseconnect/databases/";
private static String DB_NAME = "example.sqlite";
HOW TO CREATE APPS. GO HERE
The DB_PATH is the folder where the Data Bare are. The path of this are "/data/data/Pakage
Name/databases/"
And DB_NAME is the Data Base name.
You can see the Data Base in the "Android Debug Monitor". To open the Android Debug Monitor you
need go to the Android icon ( ).
Then show this:
We need to use the DDMS. This right up.
Then we select in the left the "Package name", in my case it would
be"com.example.databaseconnect"
And then in the right go to: data -> data -> package name -> database, in this folder are the Data Base.
Return to the code, you need to create, copy, check, open and then connect the Data Base to the
Device, for this in the Connect.java class create the nexts functions.
Then create another class named "DataDB.java" to connect with "Connect.java" class
And to finish in the MainActivity.java, only call the getNameDB and DONE.
Screenshots
(This page is really obsolete. We need to update these screenshots to showAndroid Studio.)
This page contains some screenshots showing the ADT in action.
Visual Layout Editor
Debugging
DDMS perspective:
Manifest editor:
Editing support for resource files:
About the Android Studio Database Example
As is probably evident from the user interface layout designed in the preceding chapter, the example project is
a simple data entry and retrieval application designed to allow the user to add, query and delete database
entries. The idea behind this application is to allow the tracking of product inventory.
The name of the database will be productID.db which, in turn, will contain a single table named products. Each
record in the database table will contain a unique product ID, a product description and the quantity of that
product item currently in stock, corresponding to column names of “productid”, “productname” and
“productquantity” respectively. The productid column will act as the primary key and will be automatically
assigned and incremented by the database management system.
The database schema for the products table is outlined in Table 42-1:
Column Data Type
productid Integer / Primary Key/ Auto Increment
productname Text
productquantity Integer
Table 42-1
Creating the Data Model
Once completed, the application will consist of an activity and a database handler class. The database handler
will be a subclass of SQLiteOpenHelper and will provide an abstract layer between the underlying SQLite
database and the activity class, with the activity calling on the database handler to interact with the database
(adding, removing and querying database entries). In order to implement this interaction in a structured way, a
third class will need to be implemented to hold the database entry data as it is passed between the activity and
the handler. This is actually a very simple class capable of holding product ID, product name and product
quantity values, together with getter and setter methods for accessing these values. Instances of this class can
then be created within the activity and database handler and passed back and forth as needed. Essentially, this
class can be thought of as representing the database model.
Within Android Studio, navigate within the Project tool window to app -> java and right-click on the package
name. From the popup menu, choose the New -> Java Class option and, in the Create New Class dialog,
name the class Product before clicking on the OK button.
Once created the Product.java source file will automatically load into the Android Studio editor. Once loaded,
modify the code to add the appropriate data members and methods:
package com.ebookfrenzy.database;
public class Product {
private int _id;
private String _productname;
private int _quantity;
public Product() {
}
public Product(int id, String productname, int quantity) {
this._id = id;
this._productname = productname;
this._quantity = quantity;
}
public Product(String productname, int quantity) {
this._productname = productname;
this._quantity = quantity;
}
public void setID(int id) {
this._id = id;
}
public int getID() {
return this._id;
}
public void setProductName(String productname) {
this._productname = productname;
}
public String getProductName() {
return this._productname;
}
public void setQuantity(int quantity) {
this._quantity = quantity;
}
public int getQuantity() {
return this._quantity;
}
}
The completed class contains private data members for the internal storage of data columns from database
entries and a set of methods to get and set those values.
Implementing the Data Handler
The data handler will be implemented by subclassing from the Android SQLiteOpenHelper class and, as
outlined in An Overview of Android SQLite Databases in Android Studio, adding the constructor, onCreate()
and onUpgrade() methods. Since the handler will be required to add, query and delete data on behalf of the
activity component, corresponding methods will also need to be added to the class.
Begin by adding a second new class to the project to act as the handler, this time named MyDBHandler. Once
the new class has been created, modify it so that it reads as follows:
package com.ebookfrenzy.database;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHandler extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
}
}
Having now pre-populated the source file with template onCreate() and onUpgrade() methods the next task is
to add a constructor method. Modify the code to declare constants for the database name, table name, table
columns and database version and to add the constructor method as follows:
package com.ebookfrenzy.database;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "productDB.db";
private static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
public static final String COLUMN_QUANTITY = "quantity";
public MyDBHandler(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
}
}
Next, the onCreate() method needs to be implemented so that the products table is created when the database
is first initialized. This involves constructing a SQL CREATE statement containing instructions to create a new
table with the appropriate columns and then passing that through to the execSQL() method of the
SQLiteDatabase object passed as an argument to onCreate():
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " +
TABLE_PRODUCTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_PRODUCTNAME
+ " TEXT," + COLUMN_QUANTITY + " INTEGER" + ")";
db.execSQL(CREATE_PRODUCTS_TABLE);
}
The onUpgrade() method is called when the handler is invoked with a greater database version number from
the one previously used. The exact steps to be performed in this instance will be application specific, so for the
purposes of this example we will simply remove the old database and create a new one:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
All that now remains to be implemented in the MyDBHandler.java handler class are the methods to add, query
and remove database table entries.
The Add Handler Method
The method to insert database records will be named addProduct() and will take as an argument an instance of
our Product data model class. A ContentValues object will be created in the body of the method and primed
with key-value pairs for the data columns extracted from the Product object. Next, a reference to the database
will be obtained via a call to getWritableDatabase() followed by a call to the insert() method of the returned
database object. Finally, once the insertion has been performed, the database needs to be closed:
public void addProduct(Product product) {
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.getProductName());
values.put(COLUMN_QUANTITY, product.getQuantity());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
The Query Handler Method
The method to query the database will be named findProduct() and will take as an argument a String object
containing the name of the product to be located. Using this string, a SQL SELECT statement will be
constructed to find all matching records in the table. For the purposes of this example, only the first match will
then be returned, contained within a new instance of our Product data model class:
public Product findProduct(String productname) {
String query = "Select * FROM " + TABLE_PRODUCTS + " WHERE " +
COLUMN_PRODUCTNAME + " = "" + productname + """;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Product product = new Product();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
product.setID(Integer.parseInt(cursor.getString(0)));
product.setProductName(cursor.getString(1));
product.setQuantity(Integer.parseInt(cursor.getString(2)));
cursor.close();
} else {
product = null;
}
db.close();
return product;
}
The Delete Handler Method
The deletion method will be named deleteProduct() and will accept as an argument the entry to be deleted in
the form of a Product object. The method will use a SQL SELECT statement to search for the entry based on
the product name and, if located, delete it from the table. The success or otherwise of the deletion will be
reflected in a Boolean return value:
public boolean deleteProduct(String productname) {
boolean result = false;
String query = "Select * FROM " + TABLE_PRODUCTS + " WHERE " +
COLUMN_PRODUCTNAME + " = "" + productname + """;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Product product = new Product();
if (cursor.moveToFirst()) {
product.setID(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_PRODUCTS, COLUMN_ID + " = ?",
new String[] { String.valueOf(product.getID()) });
cursor.close();
result = true;
}
db.close();
return result;
}
Implementing the Activity Event Methods
The final task prior to testing the application is to wire up onClick event handlers on the three buttons in the
user interface and to implement corresponding methods for those events. Locate and load the
activity_database.xml file into the Designer tool, switch to Text mode and locate and modify the three button
elements to add onClick properties:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/add_string"
android:id="@+id/button"
android:onClick="newProduct" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/find_string"
android:id="@+id/button2"
android:onClick="lookupProduct" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/delete_string"
android:id="@+id/button3"
android:onClick="removeProduct" />
Load the DatabaseActivity.java source file into the editor and implement the code to identify the views in the
user interface and to implement the three “onClick” target methods:
package com.ebookfrenzy.database;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class DatabaseActivity extends ActionBarActivity {
TextView idView;
EditText productBox;
EditText quantityBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
idView = (TextView) findViewById(R.id.productID);
productBox = (EditText) findViewById(R.id.productName);
quantityBox =
(EditText) findViewById(R.id.productQuantity);
}
public void newProduct (View view) {
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
int quantity =
Integer.parseInt(quantityBox.getText().toString());
Product product =
new Product(productBox.getText().toString(), quantity);
dbHandler.addProduct(product);
productBox.setText("");
quantityBox.setText("");
}
public void lookupProduct (View view) {
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
Product product =
dbHandler.findProduct(productBox.getText().toString());
if (product != null) {
idView.setText(String.valueOf(product.getID()));
quantityBox.setText(String.valueOf(product.getQuantity()));
} else {
idView.setText("No Match Found");
}
}
public void removeProduct (View view) {
MyDBHandler dbHandler = new MyDBHandler(this, null,
null, 1);
boolean result = dbHandler.deleteProduct(
productBox.getText().toString());
if (result)
{
idView.setText("Record Deleted");
productBox.setText("");
quantityBox.setText("");
}
else
idView.setText("No Match Found");
}
}
How to create and use a SQLite
database in Android applications
So you’ve got this data that you need to save.
Why not put it into a SQLite database?
What’s a SQLite database?
It’s a popular, open source database engine found on many small devices.
It stores data in a file on your device. The data is secure and only accessible by the app that created
it.
You can store different data types like strings, long, float, etc. without any problems.
You can also share the data with other apps if you choose to by using a Content Provider.
Working with the database
I’ll explain how to use a SQLite database with the help of an example.
I want to save the names, email addresses and phone numbers of my friends. Let’s see how it’s
done.
Do it in the background
Creating, opening and using the database takes time.
This could cause the app to hang if you use the database on the main thread.
Asynchronously
The best practice is to do all database transactions off the main thread. There are two commonly
used ways of doing this:
 Using an AsyncTask
 Using an IntentService
I won’t be discussing these in this tutorial but note that you should do all database activity off the
main thread.
Database design
Before you start to create your database, you should:
 Decide on the data that you want to save and how you want it organised
 Decide on your database name, table name and names of all the column titles
 You should also include a column for the unique row index. Although it’s only required if
you’re going to use the database with a Content Provider
Keep it constant
Make them all constants and put them in a separate class.
If you need to make changes later, it’s easy to do that here.
Quick tip
Don’t store files in the database. Rather store the file’s address.
The Contract class
The contract class contains the database constants, such as the:
 database name – myContacts_database
 table name – MyContacts_table
 version number – 1. You need to change the version number whenever you make changes
to the database structure, like adding columns for example
 column titles – name, email, phone
Our database constants: The KEY_ID is the unique index that is needed if you’re going to use the
database with a Content Provider
The SQLiteOpenHelper class
We use this class to efficiently create, open and upgrade a database.
It contains two methods:
 onCreate() – used to create a new database. This is done once only
 onUpgrade() – used to upgrade the database if the required version number is later than the
existing version
This SQL string used to create the database for the first time
Using this onUpgrade() method deletes the existing database and creates a new one. All data is lost
so you may want to first backup the data
The SQLiteDatabase class
We use this class’s methods to query and transact with the database
Opening a database
When we try and open a database, the Open Helper first checks to see if the database exists. If it
does, then the version number is checked. If it’s the latest version then it opens the database.
The SQLite Open Helper caches the opened database. This makes any future use of the database
pretty fast as an instance of it exists in memory.
It is best practice to open the database just before you are about to use it.
Creating a database
What if the database does not exist or our version is later than the existing version?
When you need to access the database, construct a subclass of
SQLiteOpenHelper, MyDbOpenHelper. Then create a helper object, dbHelper and use this to create
or open the database
When you call getWriteableDatabase(), it creates the database if it doesn’t exist and if the existing
database’s version number is outdated, then the database is deleted and a new one is created.
Which do we use, getWriteableDatabase() or getReadableDatabase()
If you’re going to write to the database, use getWriteableDatabase() to open the database.
Sometimes this can fail so it’s wise to fall back on trying to open the database using
getReadableDatabase(). In most cases, it will provide the cached writeable database or failing this, a
readable database.
Closing a database
Once opened, an instance of the database exists in memory so it makes sense not to close it until
you are sure that you will no longer be using it.
You can close it in the Activity’s onDestroy() method, for example.
Transactions and queries
You’ll need an instance of the database to do any transactions or queries.
You can add data, update data, delete data and search for data using these SQLiteDatabase
methods:
 Insert() – to put data into the database
 delete() – to delete data
 query() – to search for data
 update() – to make changes to existing data
Here’s the code for getting a database object:
First get the SQLiteOpenHelper object and then open the database. It is best practice to do this for
each query or transaction
Querying the database
Doing a search? Use the query() method. It returns a Cursor object.
The Cursor is an interface to the set of data returned by the query. It gives you access to that data.
The query returns a Cursor
The query() method’s parameters:
 the database table name
 projection – a String array of the column titles that you would like returned
 selection – this is the SQL WHERE clause that filters the rows to return
 selectionArguments – a String array of arguments for the WHERE clause
 groupBy – a filter for grouping the rows
 having – a filter for which row groups to include
 orderBy – how the rows should be ordered
The query parameters
Note the following:
 I want to get the values from all the columns (KEY_ID,NAME,EMAIL,PHONE). I could have
passed NULL here as this would return all columns by default
 I’m looking for all records with a NAME value of Reginald. Passing NULL for the WHERE
clause and argument would return all rows by default
Extract values from cursor
To get the values out of the cursor:
 position the cursor at the correct row
 use the get<type> methods to get the stored value
Here’s an example:
Using a While loop to iterate through the cursor to get the values
moveToFirst() positions the cursor at the first record.
The While loop will continue until the cursor passes the last record (when isAfterLast() is true).
The getString() method is passed the column index. These indexes are determined by the position of
the columns in our projection parameter.
Very important
You must close the cursor when you have finished using it to avoid memory leaks.
Adding a row of data
Adding a row is easy. Simply put all your data into a ContentValues object. Then pass the
ContentValues object to the insert() method as a parameter.
ContentValues objects stores the data in key/value pairs
Insert the data into the database using the insert() method.
You need three parameters:
 the database table name
 the nullColumnHack
 the data in the form of a ContentValues object
Pass the ContentValues object to the insert() method. The data is inserted into the database and the
row ID returned
NullColumnHack
When inserting a new row. Always specify at least one column and corresponding value.
If you have to add an empty row then you must pass the name of the column to set to null as the
second parameter.
An exception will be thrown if the nullColumnHack is set to null and you add an empty row.
Set this parameter to NULL as long as you’re adding data to any of the columns.
Updating rows
It’s easy to update rows in the database.
As with all queries or transactions, you must first get a database object.
Then simply put the new data into a ContentValues object and use the WHERE clause to identify the
rows that you want to update.
In this example, I want to change the name from Reginald to Roland.
I place the new name into the ContentValues object. Then I set up the WHERE clause:
This will change all the names matching Reginald to Roland
And put it all together in the update() method:
Once updated, it returns the number of rows updated
Important
If you have an open cursor, then you need to run a new query so that it reflects the changes you
made to the database by updating it.
Deleting rows
Use the delete() method to delete rows.
Get a database object.
Use the WHERE clause to identify which row or rows you want to delete then call delete():
Pass the table name, WHERE clause and its arguments to delete a row. It returns the number of
records deleted
Here’s an example of setting up the WHERE clause and its arguments to delete a specific row:
Here we target a specific row by passing the row ID as the WHERE argument
Important
If you have an open cursor, then you need to run a new query so that it reflects the changes you
made to the database by updating it.
Where can I find the database file?
You’ll find the database file in the /data/data/<package_name>/databases folder of your device but
you won’t see it with a file browser unless the device is rooted.
You will be able to access it if you’re using the emulator and Eclipse for example.
You can of course copy the file over to another folder that you have access to.
The Tutorial app
Here’s a quick overview of the tutorial app which you can download:
Pressing the Add Data button loads 5 records from a String array into the database. The row ID’s
are displayed in the LogCat. Pressing Read Data displays all the rows in a list
Pressing the MainActivity Read Data button starts a list activity and displays the data read from the
database in a list
These buttons are displayed in the activity started by pressing the More button in the MainActivity
Pressing each of these buttons first loads a row of data in the database. This is purely for
demonstration purposes to ensure that there is at least one row of data in the database.
 Delete a record – deletes a single record identified by its row id. The number of rows deleted
is displayed in the LogCat
 Find a record – queries the database to find all rows where the NAME column value matches
a given name. It returns a cursor which we loop through, displaying the rows in theLogCat
 Update a record – updates all rows where the NAME column value matches a given name.
The number of rows updated is displayed in the LogCat
I hope that you have found this tutorial helpful.
Have a look at the series of tutorials on Content Providers. Here's the first in the series, Android
Content Providers.
Importing Android Studio projects into
eclipse
You can’t import Android Studio projects into
Eclipse.
Here’s what you can do:
 Create a new project in Eclipse
 Either copy and paste the relevant files directly from Android Studio into Eclipse
 Or create new files in Eclipse and then copy and paste the code from the Android Studio files
into the new Eclipse files.
Open the Android Studio files up in a text editor then copy and paste into the new Eclipse file
The Android Studio file structure. The main folders are indicated by a yellow arrow
Looking at an Android Studio project folder in
Windows Explorer
A typical Android Studio file structure as seen in Windows Explorer. We’re interested in the folder
indicated by a yellow arrow
Opening up the dialog_tutorial folder reveals the src folder. Opening this reveals the java and res
folders. The res folder contains all the resources
Opening up the dialog_tutorial folder reveals the src folder. This contains the:
 java folder – containing the java class files (including the activities)
 res folder – this is where you’ll find the layouts, drawables, menus and values files (strings,
dimensions, colors)
 AndroidManifest.xml – this is the manifest file
Here’s a typical Eclipse project’s file structure:
The folders indicated by a yellow arrow are the important ones
Copying files directly
Class files
Copy the class files from Android Studio to Eclipse.
You may need to change the package name when you’re done.
Resource files
Shouldn’t be a problem to copy these files directly over from Android Studio to Eclipse.
AndroidManifest.xml
Probably best to edit it rather than copy directly over.
Open up the two manifest files (Android Studio and Eclipse) then copy and paste the code from the
Android Studio manifest over to the Eclipse manifest.
SQLiteDatabase is a class that allowed us to perform Create, Retrieve
, Update, and Delete data (CRUD) operation. In this tutorial we will show you
how to use SQLiteDatabase to perform CRUD operation in Android.
Tool Used
1. Android Studio 0.40
To Do
In this tutorial we will going to create an app that allow
to Create, Retrieve, Update, and Delete, student record.. Easy? ya, is easy if
you know how
Download Code
Android Studio SQLite Database Example
Table Structure
This is the Student table structure that going to use to store student detail
information, we make thing simple so we only create 3 fields as image
below
Id is primary key and also auto increment number
Screen Layout
We will create 2 screens, first screen will display all students in the database
which will look like this
Second screen which is detail screen, when user click on the listview item it
will bring user to new screen which will look like this
Code The Layout
1. Let’s start to create a project and name it SQLiteDB, and the rest of step
should be as standard, if you need guide on this step , please refer this link.
These are the basic setting i’ve set.
2. In src > main > res > layout > activity_main.xml. Add ListView, Button
into activity_main.xml and it will look like this.
activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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="com.instinctcoder.sqlitedb.MainActivity$PlaceholderFragment">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="@+id/btnAdd"
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@android:id/list"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:layout_above="@+id/btnAdd" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List All"
android:id="@+id/btnGetAll"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/btnAdd" />
</RelativeLayout>
You need to change the ListView id to android:id=”@+id/list” if you choose to
extends ListActivity in your class or else you will get error –> Your content
must have a ListView whose id attribute is ‘android.R.id.list’
3. Add another activity and we named it StudentDetail.java. The go to src >
main > res > layout > activity_student_detail.xml. Add Button, TextView
into activity_student_detail.xml and it will look like this.
activity_student_detail.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
<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="com.instinctcoder.sqlitedb.StudentDetail$PlaceholderFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Name"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Email"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="29dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Age"
android:id="@+id/textView3"
android:layout_below="@+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="29dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editTextName"
android:layout_above="@+id/textView2"
android:layout_toRightOf="@+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/editTextEmail"
android:layout_above="@+id/textView3"
android:layout_toRightOf="@+id/textView"
android:layout_alignRight="@+id/editTextName"
android:layout_alignEnd="@+id/editTextName" />
<EditText
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/editTextAge"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editTextEmail"
android:layout_alignStart="@+id/editTextEmail"
android:layout_alignRight="@+id/editTextEmail"
android:layout_alignEnd="@+id/editTextEmail" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/btnSave"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="@+id/btnClose" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:id="@+id/btnClose"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:id="@+id/btnDelete"
android:layout_alignTop="@+id/btnSave"
android:layout_toLeftOf="@+id/btnSave" />
</RelativeLayout>
4. When user click on the list item we want to show student detail activity. So
we need an unique id to retrieve student detail and this id must come from
listview. To do this we have 2 options
 The easiest way (if you like ;)) you could put id and name into listview item, and
show it to the user (bad UI design -_-‘) and when user click at the code split the
selected item and pass to student detail activity to retrieve the record. (i.e.
ID_studentname will appear on the listview item)
 Create a new simple layout to help us to retrieve student detail by student id and
hide the student id in listview item from user. (I like this, or you should do this
way :)).
So to do with 2nd approach we need to create a new layout and name
it view_student_entry.xml, and the code will look like below
view_student_entry.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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">
<TextView
android:id="@+id/student_Id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/student_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:paddingTop="6dip"
android:textSize="22sp"
android:textStyle="bold" />
</LinearLayout>
Code
1. Now let’s start code on table structure portion first – create table in Android.
Base on the table structure image above, we will create a file
name Student.java , and the code in this file will look like this
Student.java
1 package com.instinctcoder.sqlitedb;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Student {
// Labels table name
public static final String TABLE = "Student";
// Labels Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_name = "name";
public static final String KEY_email = "email";
public static final String KEY_age = "age";
// property help us to keep data
public int student_ID;
public String name;
public String email;
public int age;
}
2. In order for us to create a table for need to use these
classes SQLiteDatabase, SQLiteDatabase is the class for us to perform CRUD
function, and SQLiteOpenHelper, SQLiteOpenHelper is a helper class to
manage database creation and version management. We’ll create a class and
name it DBHelper.java and code in this file will look like this, to ease on
understand code line by line i put comment in code.
DBHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.instinctcoder.sqlitedb;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
//version number to upgrade database version
//each time if you Add, Edit table, you need to change the
//version number.
private static final int DATABASE_VERSION = 4;
// Database Name
private static final String DATABASE_NAME = "crud.db";
public DBHelper(Context context ) {
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//All necessary tables you like to create will create here
String CREATE_TABLE_STUDENT = "CREATE TABLE " + Student.TABLE + "("
+ Student.KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ Student.KEY_name + " TEXT, "
+ Student.KEY_age + " INTEGER, "
+ Student.KEY_email + " TEXT )";
db.execSQL(CREATE_TABLE_STUDENT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone!!!
db.execSQL("DROP TABLE IF EXISTS " + Student.TABLE);
// Create tables again
onCreate(db);
}
}
3. With above 2 steps, student table will be created when app get started and
now we could code the CRUD functions! Create StudentRepo.java, the
purpose of this class is to perform CRUD on the Student table. The code in
this file will look like this.
StudentRepo.java
1
2
3
4
5
6
7
8
9
10
package com.instinctcoder.sqlitedb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.HashMap;
public class StudentRepo {
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
private DBHelper dbHelper;
public StudentRepo(Context context) {
dbHelper = new DBHelper(context);
}
public int insert(Student student) {
//Open connection to write data
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Student.KEY_age, student.age);
values.put(Student.KEY_email,student.email);
values.put(Student.KEY_name, student.name);
// Inserting Row
long student_Id = db.insert(Student.TABLE, null, values);
db.close(); // Closing database connection
return (int) student_Id;
}
public void delete(int student_Id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// It's a good practice to use parameter ?, instead of concatenate string
db.delete(Student.TABLE, Student.KEY_ID + "= ?", new String[] { String.valueOf(student_Id) });
db.close(); // Closing database connection
}
public void update(Student student) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Student.KEY_age, student.age);
values.put(Student.KEY_email,student.email);
values.put(Student.KEY_name, student.name);
// It's a good practice to use parameter ?, instead of concatenate string
db.update(Student.TABLE, values, Student.KEY_ID + "= ?", new String[] {
String.valueOf(student.student_ID) });
db.close(); // Closing database connection
}
public ArrayList<HashMap<String, String>> getStudentList() {
//Open connection to read only
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
Student.KEY_ID + "," +
Student.KEY_name + "," +
Student.KEY_email + "," +
Student.KEY_age +
" FROM " + Student.TABLE;
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//Student student = new Student();
ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
HashMap<String, String> student = new HashMap<String, String>();
student.put("id", cursor.getString(cursor.getColumnIndex(Student.KEY_ID)));
student.put("name", cursor.getString(cursor.getColumnIndex(Student.KEY_name)));
studentList.add(student);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return studentList;
}
public Student getStudentById(int Id){
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
Student.KEY_ID + "," +
Student.KEY_name + "," +
Student.KEY_email + "," +
Student.KEY_age +
" FROM " + Student.TABLE
+ " WHERE " +
Student.KEY_ID + "=?";// It's a good practice to use parameter ?, instead of concatenate string
int iCount =0;
Student student = new Student();
Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(Id) } );
if (cursor.moveToFirst()) {
do {
student.student_ID =cursor.getInt(cursor.getColumnIndex(Student.KEY_ID));
student.name =cursor.getString(cursor.getColumnIndex(Student.KEY_name));
student.email =cursor.getString(cursor.getColumnIndex(Student.KEY_email));
student.age =cursor.getInt(cursor.getColumnIndex(Student.KEY_age));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return student;
}
117
}
4. When user click on the listview item we will display student detail
information on detail screen, we will have this code to do the job for us. Go
to src > main > java > StudentDetail.java. and copy this code into the class.
StudentDetail.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.instinctcoder.sqlitedb;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class StudentDetail extends ActionBarActivity implements android.view.View.OnClickListener{
Button btnSave , btnDelete;
Button btnClose;
EditText editTextName;
EditText editTextEmail;
EditText editTextAge;
private int _Student_Id=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_detail);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnClose = (Button) findViewById(R.id.btnClose);
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextAge = (EditText) findViewById(R.id.editTextAge);
btnSave.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnClose.setOnClickListener(this);
_Student_Id =0;
Intent intent = getIntent();
_Student_Id =intent.getIntExtra("student_Id", 0);
StudentRepo repo = new StudentRepo(this);
Student student = new Student();
student = repo.getStudentById(_Student_Id);
editTextAge.setText(String.valueOf(student.age));
editTextName.setText(student.name);
editTextEmail.setText(student.email);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.student_detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View view) {
if (view == findViewById(R.id.btnSave)){
StudentRepo repo = new StudentRepo(this);
Student student = new Student();
student.age= Integer.parseInt(editTextAge.getText().toString());
student.email=editTextEmail.getText().toString();
student.name=editTextName.getText().toString();
student.student_ID=_Student_Id;
if (_Student_Id==0){
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
_Student_Id = repo.insert(student);
Toast.makeText(this,"New Student Insert",Toast.LENGTH_SHORT).show();
}else{
repo.update(student);
Toast.makeText(this,"Student Record updated",Toast.LENGTH_SHORT).show();
}
}else if (view== findViewById(R.id.btnDelete)){
StudentRepo repo = new StudentRepo(this);
repo.delete(_Student_Id);
Toast.makeText(this, "Student Record Deleted", Toast.LENGTH_SHORT);
finish();
}else if (view== findViewById(R.id.btnClose)){
finish();
}
}
}
5. We have almost all pieces in place to display data for us in listview. So we
continue in MainActivity.java, paste this code into file.
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.instinctcoder.sqlitedb;
import android.app.ListActivity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity implements android.view.View.OnClickListener{
Button btnAdd,btnGetAll;
TextView student_Id;
@Override
public void onClick(View view) {
if (view== findViewById(R.id.btnAdd)){
Intent intent = new Intent(this,StudentDetail.class);
intent.putExtra("student_Id",0);
startActivity(intent);
}else {
StudentRepo repo = new StudentRepo(this);
ArrayList<HashMap<String, String>> studentList = repo.getStudentList();
if(studentList.size()!=0) {
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
student_Id = (TextView) view.findViewById(R.id.student_Id);
String studentId = student_Id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),StudentDetail.class);
objIndent.putExtra("student_Id", Integer.parseInt( studentId));
startActivity(objIndent);
}
});
ListAdapter adapter = new SimpleAdapter( MainActivity.this,studentList,
R.layout.view_student_entry, new String[] { "id","name"}, new int[] {R.id.student_Id,
R.id.student_name});
setListAdapter(adapter);
}else{
Toast.makeText(this,"No student!",Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
btnGetAll = (Button) findViewById(R.id.btnGetAll);
btnGetAll.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
6. That’s all, Run! You should see the below result.
If everything go smooth, database will be created in this path “data > data >
SQLiteDB > databases > crud.db”, if you like to browse data and table
structure of the database you could refer to How to browse Android Emulator
SQLite Database
What’s next?
So far we have showed you how to CRUD data locally without needed access
internet, the next post we will show you how to pass data back to server and
save in the SQL Server, How to Call ASP.Net Web API from Android Studio.
Updated on 18 Mar 2015
This step is optional and only for those who are using eclipse
I noticed some reader had stuck in the StudentDetail.java file when they use
Eclipse to try out this tutorial, the reason why you click “Add” and failed is
because you need to import android-support-v4.jar and android-support-v7-
appcompat.jar into your workspace, the detail you could follow this link
Alternatively, you use the this source code which build in Eclipse IDE
23.0.2.1259578 and the only different with the Android Studio version is below
code
StudentDetail.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.instinctcoder.sqlitedb;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class StudentDetail extends Activity implements android.view.View.OnClickListener{
Button btnSave , btnDelete;
Button btnClose;
EditText editTextName;
EditText editTextEmail;
EditText editTextAge;
private int _Student_Id=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_detail);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnClose = (Button) findViewById(R.id.btnClose);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextAge = (EditText) findViewById(R.id.editTextAge);
btnSave.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnClose.setOnClickListener(this);
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
_Student_Id =0;
Intent intent = getIntent();
_Student_Id =intent.getIntExtra("student_Id", 0);
StudentRepo repo = new StudentRepo(this);
Student student = new Student();
student = repo.getStudentById(_Student_Id);
editTextAge.setText(String.valueOf(student.age));
editTextName.setText(student.name);
editTextEmail.setText(student.email);
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
if (view == findViewById(R.id.btnSave)){
StudentRepo repo = new StudentRepo(this);
Student student = new Student();
student.age= Integer.parseInt(editTextAge.getText().toString());
student.email=editTextEmail.getText().toString();
student.name=editTextName.getText().toString();
student.student_ID=_Student_Id;
if (_Student_Id==0){
_Student_Id = repo.insert(student);
Toast.makeText(this,"New Student Insert",Toast.LENGTH_SHORT).show();
}else{
repo.update(student);
Toast.makeText(this,"Student Record updated",Toast.LENGTH_SHORT).show();
}
}else if (view== findViewById(R.id.btnDelete)){
StudentRepo repo = new StudentRepo(this);
repo.delete(_Student_Id);
Toast.makeText(this, "Student Record Deleted", Toast.LENGTH_SHORT);
finish();
}else if (view== findViewById(R.id.btnClose)){
finish();
}
}
}
In this tutorial I will show how to use a database in Android by creating the tables and columns using
the SQLite Database Browser.1. So the first step is to download the SQLite Database Browser2. Make a new
project and name the main java class that generates with the project “MyActivity”.
3. Now you have to go to the SQLite Database Browser that you have just downloaded and run it. Here you
have to create the tables, the columns etc. I will show you how in the following lines, so pay
attention
 Create a newdatabase
To create a new database go to File – New Database and click it.
Now you will have to name your database as “database” and save it in your project in the
folder “assets”. To do this navigate to where your project is created, open the folder assets, then in the File
Name field enter the name “database” and press the Save button.
 Populate the database
Before to create the tables for your project, you have to create a specific table
called “android_metadata” with a column called “locale” and a record called “en_US”. If we don’t create
this table you will get a force close. To add the column “locale”press on the Add button like in the picture
bellow.
Now enter the name of the column and the type like in the picture bellow:
The column is created now, so the last thing you have to do is to confirm the creation of the table by pressing
on the Createlike in the picture bellow:
Now that the table and the column are created you have to enter the record “en_US”. Go to “Browse
Data” and press on theNew Record button.
An empty record will be added so you will have to edit it by double clicking on it. A new window will appear
and in that window you must put “en_US” text.
And finally we can create our own tables. You must create a table called “People”, with 2 columns: one
called “Name” and the other one called “_id” . Technically the field _id is not required, however if
you will use of the CursorAdapter class then you it is required .To create a new table follow the steps
from the picture bellow:
Now you must add the column “_id” too so press the Add button and enter the information like in the picture:
NOTE: Don’t forget to SAVE the database changes.
4. Now we have to start coding.
 First you have to create a new class called “ApplicationContextProvider” which will provide the
context wherever in the application. The code looks like this:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import android.app.Application;
import android.content.Context;
public class ApplicationContextProvider extends Application {
/**
* Keeps a reference of the application context
*/
privatestatic Context sContext;
@Override
public void onCreate() {
super.onCreate();
sContext = getApplicationContext();
}
/**
* Returns the application context
*
* @return application context
*/
public staticContext getContext() {
return sContext;
}
}
Now you have to declare this class in the AndroidManifest.xml in the application tag:
XHTML
1
2
<application android:name=".ApplicationContextProvider"
android:label="@string/app_name">
 Create a new class for database code, called “DataBaseManager”. The code looks like this:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DataBaseManager extends SQLiteOpenHelper {
// TheAndroid's default systempath of your application database.
//data/data/ and /databases remain the same always. The one that must be changed is com.example which represents
//the MAIN package of your project
privatestatic String DB_PATH = "/data/data/com.example/databases/";
//the name of your database
privatestatic String DB_NAME = "database";
privatestatic SQLiteDatabase mDataBase;
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
privatestatic DataBaseManager sInstance = null;
// database version
privatestatic final int DATABASE_VERSION = 1;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*/
privateDataBaseManager() {
super(ApplicationContextProvider.getContext(), DB_NAME, null, DATABASE_VERSION);
try {
createDataBase();
openDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Singleton for DataBase
*
* @return singleton instance
*/
public staticDataBaseManager instance() {
if (sInstance == null) {
sInstance = new DataBaseManager();
}
return sInstance;
}
/**
* Creates a empty database on thesystemand rewrites it with your own
* database.
*
* @throws java.io.IOException io exception
*/
privatevoid createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method an empty databasewill be created into
// thedefault systempath
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copyingdatabase");
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open theapplication.
*
* @return trueif it exists, false if it doesn't
*/
privateboolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database doesn't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
/**
* Copies your database from your local assets-folder to the just created
* empty databasein thesystemfolder, from where it can be accessed and
* handled. This is done by transfering bytestream.
*
* @throws java.io.IOException io exception
*/
public void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStreammyInput = ApplicationContextProvider.getContext().getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open theempty db as the output stream
OutputStream myOutput= new FileOutputStream(outFileName);
// transfer bytes from the inputfileto theoutputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
myInput.close();
}
privatevoid openDataBase() throws SQLException {
// Open thedatabase
String myPath = DB_PATH + DB_NAME;
mDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
/**
* Select method
*
* @param query select query
* @return - Cursor with theresults
* @throws android.database.SQLException sql exception
*/
public Cursor select(String query) throws SQLException {
return mDataBase.rawQuery(query, null);
}
/**
* Insert method
*
* @param table - name of the table
* @param values values to insert
* @throws android.database.SQLException sql exception
*/
public void insert(String table, ContentValues values) throws SQLException {
mDataBase.insert(table, null, values);
}
/**
* Delete method
*
* @param table - table name
* @param where WHERE clause, if pass null, all therows will be deleted
* @throws android.database.SQLException sql exception
*/
public void delete(String table, String where) throws SQLException {
mDataBase.delete(table, where, null);
}
/**
* Updatemethod
*
* @param table - table name
* @param values - values to update
* @param where - WHERE clause, if pass null, all rows will be updated
*/
public void update(String table, ContentValues values, String where) {
mDataBase.update(table, values, where, null);
}
/**
* Let you make a raw query
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
*
* @param command - the sql comand you want to run
*/
public void sqlCommand(String command) {
mDataBase.execSQL(command);
}
@Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Now please pay attention at private static String DB_PATH = “/data/data/com.example/databases/”;
and private static String DB_NAME = “database”; This two variable must be changed depending of your
project. DB_PATH general code looks like this:
Java
1 privatestatic String DB_PATH = "/data/data/YOUR_MAIN_PACKAGE/databases/";
But what “MAIN_PACKAGE” means? For example let’s imagine that we have a main package called
“com.example” and inside this package we have another package called “com.example.utils”. If the
DataBaseManager is situated in the “com.example.utils” package the DB_PATH will be:
Java
1 privatestatic String DB_PATH = "/data/data/com.example/databases/";
and NOT:
Java
1 privatestatic String DB_PATH = "/data/data/com.example.utils/databases/";
And DB_NAME general code looks like this:
Java
1 privatestatic String DB_NAME = "YOUR_DATABASE_NAME";
 Now go to “res – layout – main.xml” and put the following code. We create a text view to see the
names and 3 buttons for: Insert, Update and Delete.
XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns: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:id="@+id/name_1"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/insert"
android:text="INSERT"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/update"
android:text="UPDATE"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/delete"
android:text="DELETE"/>
</LinearLayout>
 Now go to the “MyActivity” class and put this code:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MyActivity extends Activity
{
privateDataBaseManager dataBase;
privateButton insertButton;
privateButton updateButton;
privateButton deleteButton;
privateTextView textView;
//put the table name and column in constants
public staticfinal String TABLE_NAME = "People";
public staticfinal String COLUMN_NAME = "name";
/** Called when theactivity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//creates and open thedatabase so we can use it
dataBase = DataBaseManager.instance();
textView = (TextView)findViewById(R.id.name_1);
insertButton = (Button)findViewById(R.id.insert);
updateButton = (Button)findViewById(R.id.update);
deleteButton = (Button)findViewById(R.id.delete);
insertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//with ContentValues put thedata we want into the database
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, "Diana");
//here we insert the data we have put in values
dataBase.insert(TABLE_NAME, values);
updateTextView();
}
});
updateButton.setOnClickListener(new View.OnClickListener() {
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
@Override
public void onClick(View view) {
//with ContentValues put thedata we want into the database
ContentValues values = new ContentValues();
values.put(COLUMN_NAME,"George");
//here we replace the record which has the_id=1 with thegiven name in thevalues "George"
dataBase.update(TABLE_NAME, values, "_id=1");
updateTextView();
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//here we delete the record which has the"name=George"
dataBase.delete(TABLE_NAME,"name='George'");
updateTextView();
}
});
}
public void updateTextView(){
//to get data from database we need a cursor.
//after we performa select query all the data from database specific for the query, will be in the cursor
// "*" means "all" in translation the query means "SELECT ALL FROM NAMETABLE"
Cursor cursor = dataBase.select("SELECT * FROM " + TABLE_NAME);
textView.setText("");
//the cursor iterates the column "name"
while (cursor.moveToNext()){
//in this string we get the record for each row from thecolumn "name"
String s = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));
//in this textView will be added, updated or deleted thestring
// "n" means "new line"
textView.append("n" + s);
}
//here we close the cursor because we do not longer need it
cursor.close();
}
}
So, as you can see you can perform the following action on the database:
INSERT, UPDATE, DELETE and SELECT.
The general code for INSERT into database is:
Java
1
2
3
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, "WHAT YOU WANT TO INSERT");
dataBase.insert(TABLE_NAME, values);
The general code for UPDATE something from database is:
Java
1
2
3
ContentValues values = new ContentValues();
values.put(COLUMN_NAME,"VALUE WITH WHICH YOU WANT TO UPDATE");
dataBase.update(TABLE_NAME, values, WHERE CLAUSE like "id='1'" or name="sam" etc);
The general code for DELETE something from database is:
Java
1 dataBase.delete(TABLE_NAME,WHERE CLAUSE like "name='George'");
The general code for SELECT something from database is:
NOTE: If you make any changes to the database (create a newtable, or a newcolumn etc) you must
uninstall your project from emulator or test device and run again your project. You have to do this
because the previous database doesn’t update “in real time” with changes you make on it’s structure.
Now you can test the application
INSERT UPDATE
DELETE
SQLite is a opensource 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
Database - Package
The main package is android.database.sqlite that contains the classes to
manage your own databases
Database - Creation
In order to create a database you just need to call this method
openOrCreateDatabase 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
SQLiteDatabse mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);
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, SQLiteDatabase.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()
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(1);
String password = resultSet.getString(2);
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 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.
s
Steps Description
1 You will use Android studio to create an Android application under
a package com.example.sairamkrishna.myapplication. While
creating this project, make sure you Target SDK and Compile With
at the latest version of Android SDK to use higher levels of APIs.
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;
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);
}
});
}
@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
activityDisplayContact.java
package com.example.addressbook;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
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));
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.main, menu);
}
}
return true;
}
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
}
});
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
package com.example.addressbook;
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)
{
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>();
//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
<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"
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
<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">
<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"
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
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
<?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
<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>
</activity>
<activity android:name=".DisplayContact"/>
</application>
</manifest>
Creating a SQLite database app
Create a new Android mobile application solution in Xamarin Studio
If you don't have Xamarin Studio, don't worry. You can download it
here: Xamarin Studio
Database class
1. Right click project BD_Demo --> Add --> New File… --> Android Class
(Database)
Database class is for handling SQLiteDatabase object. We are now going to
create objects and methods for handling CRUD (Create, Read, Update and
Delete) operations in a database table. Here is the code:
//Required assemblies
using Android.Database.Sqlite;
using System.IO;
namespace BD_Demo
{
class Database
{
//SQLiteDatabase object for database handling
private SQLiteDatabase sqldb;
//String for Query handling
private string sqldb_query;
//String for Message handling
private string sqldb_message;
//Bool to check for database availability
private bool sqldb_available;
//Zero argument constructor, initializes a new instance of Database class
public Database()
{
sqldb_message = "";
sqldb_available = false;
}
//One argument constructor, initializes a new instance of Database class
with database name parameter
public Database(string sqldb_name)
{
try
{
sqldb_message = "";
sqldb_available = false;
CreateDatabase(sqldb_name);
}
catch (SQLiteException ex)
{
sqldb_message = ex.Message;
}
}
//Gets or sets value depending on database availability
public bool DatabaseAvailable
{
get{ return sqldb_available; }
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples
Android sql examples

More Related Content

What's hot

A pain free migraine
A pain free migraineA pain free migraine
A pain free migraineDennis Solis
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml datakendyhuu
 
CaseStudy-MohammedImranAlam-Xcelsius
CaseStudy-MohammedImranAlam-XcelsiusCaseStudy-MohammedImranAlam-Xcelsius
CaseStudy-MohammedImranAlam-XcelsiusMohammed Imran Alam
 
Visualizing STEP Files
Visualizing STEP FilesVisualizing STEP Files
Visualizing STEP FilesRichard Haney
 
Disconnected data
Disconnected dataDisconnected data
Disconnected dataaspnet123
 
Ado.net session05
Ado.net session05Ado.net session05
Ado.net session05Niit Care
 
Ado.net session02
Ado.net session02Ado.net session02
Ado.net session02Niit Care
 
Laboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y Salto
Laboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y SaltoLaboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y Salto
Laboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y SaltoGeneXus
 
11 qmds2005 session16
11 qmds2005 session1611 qmds2005 session16
11 qmds2005 session16Niit Care
 
Ado.net session04
Ado.net session04Ado.net session04
Ado.net session04Niit Care
 
Ado.net session01
Ado.net session01Ado.net session01
Ado.net session01Niit Care
 

What's hot (19)

A pain free migraine
A pain free migraineA pain free migraine
A pain free migraine
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml data
 
CaseStudy-MohammedImranAlam-Xcelsius
CaseStudy-MohammedImranAlam-XcelsiusCaseStudy-MohammedImranAlam-Xcelsius
CaseStudy-MohammedImranAlam-Xcelsius
 
Visualizing STEP Files
Visualizing STEP FilesVisualizing STEP Files
Visualizing STEP Files
 
Disconnected data
Disconnected dataDisconnected data
Disconnected data
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ado.net session05
Ado.net session05Ado.net session05
Ado.net session05
 
Prg421
Prg421Prg421
Prg421
 
Exercises
ExercisesExercises
Exercises
 
Ado.net session02
Ado.net session02Ado.net session02
Ado.net session02
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
Chapter6 database connectivity
Chapter6 database connectivityChapter6 database connectivity
Chapter6 database connectivity
 
Laboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y Salto
Laboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y SaltoLaboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y Salto
Laboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y Salto
 
11 qmds2005 session16
11 qmds2005 session1611 qmds2005 session16
11 qmds2005 session16
 
Ado.net session04
Ado.net session04Ado.net session04
Ado.net session04
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Ado.net session01
Ado.net session01Ado.net session01
Ado.net session01
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 

Viewers also liked (17)

Ch20
Ch20Ch20
Ch20
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
 
Advancedrn
AdvancedrnAdvancedrn
Advancedrn
 
Going beyond-data-and-analytics-v4
Going beyond-data-and-analytics-v4Going beyond-data-and-analytics-v4
Going beyond-data-and-analytics-v4
 
worklight_development_environment
worklight_development_environmentworklight_development_environment
worklight_development_environment
 
Collaborative filtering hyoungtae cho
Collaborative filtering hyoungtae choCollaborative filtering hyoungtae cho
Collaborative filtering hyoungtae cho
 
Caqa5e ch4
Caqa5e ch4Caqa5e ch4
Caqa5e ch4
 
Asp controls
Asp  controlsAsp  controls
Asp controls
 
Lec13 cdn
Lec13 cdnLec13 cdn
Lec13 cdn
 
Role of locking- cds
Role of locking- cdsRole of locking- cds
Role of locking- cds
 
Cdn imw01
Cdn imw01Cdn imw01
Cdn imw01
 
Des
DesDes
Des
 
Intellij idea features
Intellij idea featuresIntellij idea features
Intellij idea features
 
(148064384) bfs
(148064384) bfs(148064384) bfs
(148064384) bfs
 
Big data trendsdirections nimführ.ppt
Big data trendsdirections nimführ.pptBig data trendsdirections nimführ.ppt
Big data trendsdirections nimführ.ppt
 
Hans enocson how big data creates opportunities for productivity improvements...
Hans enocson how big data creates opportunities for productivity improvements...Hans enocson how big data creates opportunities for productivity improvements...
Hans enocson how big data creates opportunities for productivity improvements...
 
Visual studio-2012-product-guide
Visual studio-2012-product-guideVisual studio-2012-product-guide
Visual studio-2012-product-guide
 

Similar to Android sql examples

I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfConint29
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptxvishal choudhary
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenSony Suci
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android ApplicationMark Lester Navarro
 
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...mauricemuteti2015
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving DataAnuchit Chalothorn
 
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx        Greetings and Salutations.docxCIS407AWk2iLabDefault.aspx        Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docxclarebernice
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorialinfo_zybotech
 
Volley lab btc_bbit
Volley lab btc_bbitVolley lab btc_bbit
Volley lab btc_bbitCarWash1
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletMitchinson
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guideFahad Shiekh
 

Similar to Android sql examples (20)

I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdf
 
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
 
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...
(CRUD) How To Connect To Microsoft Access Database Insert Update Delete Clear...
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
F1
F1F1
F1
 
ALL NEW OOP 2014
ALL NEW OOP 2014ALL NEW OOP 2014
ALL NEW OOP 2014
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
 
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx        Greetings and Salutations.docxCIS407AWk2iLabDefault.aspx        Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Volley lab btc_bbit
Volley lab btc_bbitVolley lab btc_bbit
Volley lab btc_bbit
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
9 content-providers
9 content-providers9 content-providers
9 content-providers
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutlet
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guide
 

Recently uploaded

Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 

Recently uploaded (20)

Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 

Android sql examples

  • 1. Android Developer m a r t e s , 7 d e e n e r o d e 2 0 1 4 Connect DB SQLite to Android With Android Studio Connect DB SQLite to Android With Android Studio CREATE FAST APPS HERE DOWNLOAD ALL THE PROYECT HERE One of the first and more important information are: How to connect SQLite with Android app? For this tutorial I am using Android Studio. You can download this from HERE First we need to create we database. I am using SQLite Manager (this is a plugin for Firefox). I create a Data Base named "example" and a table named "exampleTable". CREATE TABLE exampleTable ( name VARCHAR(200) NULL DEFAULT NULL, lastname VARCHAR(200) NULL DEFAULT NULL, ID VARCHAR(20) NULL DEFAULT NULL ) INSERT INTO exampleTable VALUES('Jhon', 'Sweet', '1'); INSERT INTO exampleTable VALUES('Audrey', 'Owen', '2'); INSERT INTO exampleTable VALUES('Michelle', 'Peters', '3'); INSERT INTO exampleTable VALUES('Helen', 'Black', '4'); INSERT INTO exampleTable VALUES('Jessica', 'Sweet', '5'); When the database are create, we need to put in the assent folder, in the Android Studio Proyect.
  • 2. Then we create a Connection class. In this class are two important lines in this class: private static String DB_PATH = "/data/data/com.example.databaseconnect/databases/"; private static String DB_NAME = "example.sqlite"; HOW TO CREATE APPS. GO HERE The DB_PATH is the folder where the Data Bare are. The path of this are "/data/data/Pakage Name/databases/" And DB_NAME is the Data Base name. You can see the Data Base in the "Android Debug Monitor". To open the Android Debug Monitor you
  • 3. need go to the Android icon ( ). Then show this: We need to use the DDMS. This right up. Then we select in the left the "Package name", in my case it would be"com.example.databaseconnect" And then in the right go to: data -> data -> package name -> database, in this folder are the Data Base. Return to the code, you need to create, copy, check, open and then connect the Data Base to the Device, for this in the Connect.java class create the nexts functions.
  • 4. Then create another class named "DataDB.java" to connect with "Connect.java" class
  • 5. And to finish in the MainActivity.java, only call the getNameDB and DONE. Screenshots (This page is really obsolete. We need to update these screenshots to showAndroid Studio.) This page contains some screenshots showing the ADT in action. Visual Layout Editor
  • 7. Manifest editor: Editing support for resource files:
  • 8. About the Android Studio Database Example As is probably evident from the user interface layout designed in the preceding chapter, the example project is a simple data entry and retrieval application designed to allow the user to add, query and delete database entries. The idea behind this application is to allow the tracking of product inventory. The name of the database will be productID.db which, in turn, will contain a single table named products. Each record in the database table will contain a unique product ID, a product description and the quantity of that product item currently in stock, corresponding to column names of “productid”, “productname” and “productquantity” respectively. The productid column will act as the primary key and will be automatically assigned and incremented by the database management system. The database schema for the products table is outlined in Table 42-1: Column Data Type productid Integer / Primary Key/ Auto Increment productname Text productquantity Integer Table 42-1 Creating the Data Model Once completed, the application will consist of an activity and a database handler class. The database handler will be a subclass of SQLiteOpenHelper and will provide an abstract layer between the underlying SQLite database and the activity class, with the activity calling on the database handler to interact with the database
  • 9. (adding, removing and querying database entries). In order to implement this interaction in a structured way, a third class will need to be implemented to hold the database entry data as it is passed between the activity and the handler. This is actually a very simple class capable of holding product ID, product name and product quantity values, together with getter and setter methods for accessing these values. Instances of this class can then be created within the activity and database handler and passed back and forth as needed. Essentially, this class can be thought of as representing the database model. Within Android Studio, navigate within the Project tool window to app -> java and right-click on the package name. From the popup menu, choose the New -> Java Class option and, in the Create New Class dialog, name the class Product before clicking on the OK button. Once created the Product.java source file will automatically load into the Android Studio editor. Once loaded, modify the code to add the appropriate data members and methods: package com.ebookfrenzy.database; public class Product { private int _id; private String _productname; private int _quantity; public Product() { } public Product(int id, String productname, int quantity) { this._id = id; this._productname = productname; this._quantity = quantity; } public Product(String productname, int quantity) { this._productname = productname; this._quantity = quantity; } public void setID(int id) { this._id = id; } public int getID() { return this._id; } public void setProductName(String productname) { this._productname = productname; }
  • 10. public String getProductName() { return this._productname; } public void setQuantity(int quantity) { this._quantity = quantity; } public int getQuantity() { return this._quantity; } } The completed class contains private data members for the internal storage of data columns from database entries and a set of methods to get and set those values. Implementing the Data Handler The data handler will be implemented by subclassing from the Android SQLiteOpenHelper class and, as outlined in An Overview of Android SQLite Databases in Android Studio, adding the constructor, onCreate() and onUpgrade() methods. Since the handler will be required to add, query and delete data on behalf of the activity component, corresponding methods will also need to be added to the class. Begin by adding a second new class to the project to act as the handler, this time named MyDBHandler. Once the new class has been created, modify it so that it reads as follows: package com.ebookfrenzy.database; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class MyDBHandler extends SQLiteOpenHelper { @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
  • 11. Having now pre-populated the source file with template onCreate() and onUpgrade() methods the next task is to add a constructor method. Modify the code to declare constants for the database name, table name, table columns and database version and to add the constructor method as follows: package com.ebookfrenzy.database; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.content.Context; import android.content.ContentValues; import android.database.Cursor; public class MyDBHandler extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "productDB.db"; private static final String TABLE_PRODUCTS = "products"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_PRODUCTNAME = "productname"; public static final String COLUMN_QUANTITY = "quantity"; public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, DATABASE_NAME, factory, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } Next, the onCreate() method needs to be implemented so that the products table is created when the database is first initialized. This involves constructing a SQL CREATE statement containing instructions to create a new table with the appropriate columns and then passing that through to the execSQL() method of the SQLiteDatabase object passed as an argument to onCreate(): @Override public void onCreate(SQLiteDatabase db) {
  • 12. String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_PRODUCTNAME + " TEXT," + COLUMN_QUANTITY + " INTEGER" + ")"; db.execSQL(CREATE_PRODUCTS_TABLE); } The onUpgrade() method is called when the handler is invoked with a greater database version number from the one previously used. The exact steps to be performed in this instance will be application specific, so for the purposes of this example we will simply remove the old database and create a new one: @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS); onCreate(db); } All that now remains to be implemented in the MyDBHandler.java handler class are the methods to add, query and remove database table entries. The Add Handler Method The method to insert database records will be named addProduct() and will take as an argument an instance of our Product data model class. A ContentValues object will be created in the body of the method and primed with key-value pairs for the data columns extracted from the Product object. Next, a reference to the database will be obtained via a call to getWritableDatabase() followed by a call to the insert() method of the returned database object. Finally, once the insertion has been performed, the database needs to be closed: public void addProduct(Product product) { ContentValues values = new ContentValues(); values.put(COLUMN_PRODUCTNAME, product.getProductName()); values.put(COLUMN_QUANTITY, product.getQuantity()); SQLiteDatabase db = this.getWritableDatabase(); db.insert(TABLE_PRODUCTS, null, values); db.close(); } The Query Handler Method The method to query the database will be named findProduct() and will take as an argument a String object containing the name of the product to be located. Using this string, a SQL SELECT statement will be constructed to find all matching records in the table. For the purposes of this example, only the first match will then be returned, contained within a new instance of our Product data model class:
  • 13. public Product findProduct(String productname) { String query = "Select * FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + " = "" + productname + """; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query, null); Product product = new Product(); if (cursor.moveToFirst()) { cursor.moveToFirst(); product.setID(Integer.parseInt(cursor.getString(0))); product.setProductName(cursor.getString(1)); product.setQuantity(Integer.parseInt(cursor.getString(2))); cursor.close(); } else { product = null; } db.close(); return product; } The Delete Handler Method The deletion method will be named deleteProduct() and will accept as an argument the entry to be deleted in the form of a Product object. The method will use a SQL SELECT statement to search for the entry based on the product name and, if located, delete it from the table. The success or otherwise of the deletion will be reflected in a Boolean return value: public boolean deleteProduct(String productname) { boolean result = false; String query = "Select * FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + " = "" + productname + """; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query, null); Product product = new Product(); if (cursor.moveToFirst()) { product.setID(Integer.parseInt(cursor.getString(0))); db.delete(TABLE_PRODUCTS, COLUMN_ID + " = ?", new String[] { String.valueOf(product.getID()) });
  • 14. cursor.close(); result = true; } db.close(); return result; } Implementing the Activity Event Methods The final task prior to testing the application is to wire up onClick event handlers on the three buttons in the user interface and to implement corresponding methods for those events. Locate and load the activity_database.xml file into the Designer tool, switch to Text mode and locate and modify the three button elements to add onClick properties: <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/add_string" android:id="@+id/button" android:onClick="newProduct" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/find_string" android:id="@+id/button2" android:onClick="lookupProduct" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/delete_string" android:id="@+id/button3" android:onClick="removeProduct" /> Load the DatabaseActivity.java source file into the editor and implement the code to identify the views in the user interface and to implement the three “onClick” target methods: package com.ebookfrenzy.database; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText;
  • 15. import android.widget.TextView; public class DatabaseActivity extends ActionBarActivity { TextView idView; EditText productBox; EditText quantityBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_database); idView = (TextView) findViewById(R.id.productID); productBox = (EditText) findViewById(R.id.productName); quantityBox = (EditText) findViewById(R.id.productQuantity); } public void newProduct (View view) { MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1); int quantity = Integer.parseInt(quantityBox.getText().toString()); Product product = new Product(productBox.getText().toString(), quantity); dbHandler.addProduct(product); productBox.setText(""); quantityBox.setText(""); } public void lookupProduct (View view) { MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1); Product product = dbHandler.findProduct(productBox.getText().toString()); if (product != null) { idView.setText(String.valueOf(product.getID())); quantityBox.setText(String.valueOf(product.getQuantity())); } else { idView.setText("No Match Found"); } }
  • 16. public void removeProduct (View view) { MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1); boolean result = dbHandler.deleteProduct( productBox.getText().toString()); if (result) { idView.setText("Record Deleted"); productBox.setText(""); quantityBox.setText(""); } else idView.setText("No Match Found"); } } How to create and use a SQLite database in Android applications So you’ve got this data that you need to save. Why not put it into a SQLite database? What’s a SQLite database?
  • 17. It’s a popular, open source database engine found on many small devices. It stores data in a file on your device. The data is secure and only accessible by the app that created it. You can store different data types like strings, long, float, etc. without any problems. You can also share the data with other apps if you choose to by using a Content Provider. Working with the database I’ll explain how to use a SQLite database with the help of an example. I want to save the names, email addresses and phone numbers of my friends. Let’s see how it’s done. Do it in the background Creating, opening and using the database takes time. This could cause the app to hang if you use the database on the main thread. Asynchronously The best practice is to do all database transactions off the main thread. There are two commonly used ways of doing this:  Using an AsyncTask  Using an IntentService I won’t be discussing these in this tutorial but note that you should do all database activity off the main thread. Database design Before you start to create your database, you should:  Decide on the data that you want to save and how you want it organised  Decide on your database name, table name and names of all the column titles  You should also include a column for the unique row index. Although it’s only required if you’re going to use the database with a Content Provider Keep it constant Make them all constants and put them in a separate class. If you need to make changes later, it’s easy to do that here. Quick tip Don’t store files in the database. Rather store the file’s address. The Contract class The contract class contains the database constants, such as the:
  • 18.  database name – myContacts_database  table name – MyContacts_table  version number – 1. You need to change the version number whenever you make changes to the database structure, like adding columns for example  column titles – name, email, phone Our database constants: The KEY_ID is the unique index that is needed if you’re going to use the database with a Content Provider The SQLiteOpenHelper class We use this class to efficiently create, open and upgrade a database. It contains two methods:  onCreate() – used to create a new database. This is done once only  onUpgrade() – used to upgrade the database if the required version number is later than the existing version This SQL string used to create the database for the first time
  • 19. Using this onUpgrade() method deletes the existing database and creates a new one. All data is lost so you may want to first backup the data The SQLiteDatabase class We use this class’s methods to query and transact with the database Opening a database When we try and open a database, the Open Helper first checks to see if the database exists. If it does, then the version number is checked. If it’s the latest version then it opens the database. The SQLite Open Helper caches the opened database. This makes any future use of the database pretty fast as an instance of it exists in memory. It is best practice to open the database just before you are about to use it. Creating a database What if the database does not exist or our version is later than the existing version? When you need to access the database, construct a subclass of SQLiteOpenHelper, MyDbOpenHelper. Then create a helper object, dbHelper and use this to create or open the database When you call getWriteableDatabase(), it creates the database if it doesn’t exist and if the existing database’s version number is outdated, then the database is deleted and a new one is created. Which do we use, getWriteableDatabase() or getReadableDatabase() If you’re going to write to the database, use getWriteableDatabase() to open the database. Sometimes this can fail so it’s wise to fall back on trying to open the database using getReadableDatabase(). In most cases, it will provide the cached writeable database or failing this, a readable database. Closing a database Once opened, an instance of the database exists in memory so it makes sense not to close it until you are sure that you will no longer be using it. You can close it in the Activity’s onDestroy() method, for example. Transactions and queries You’ll need an instance of the database to do any transactions or queries. You can add data, update data, delete data and search for data using these SQLiteDatabase methods:  Insert() – to put data into the database  delete() – to delete data  query() – to search for data  update() – to make changes to existing data
  • 20. Here’s the code for getting a database object: First get the SQLiteOpenHelper object and then open the database. It is best practice to do this for each query or transaction Querying the database Doing a search? Use the query() method. It returns a Cursor object. The Cursor is an interface to the set of data returned by the query. It gives you access to that data. The query returns a Cursor The query() method’s parameters:  the database table name
  • 21.  projection – a String array of the column titles that you would like returned  selection – this is the SQL WHERE clause that filters the rows to return  selectionArguments – a String array of arguments for the WHERE clause  groupBy – a filter for grouping the rows  having – a filter for which row groups to include  orderBy – how the rows should be ordered The query parameters Note the following:  I want to get the values from all the columns (KEY_ID,NAME,EMAIL,PHONE). I could have passed NULL here as this would return all columns by default  I’m looking for all records with a NAME value of Reginald. Passing NULL for the WHERE clause and argument would return all rows by default Extract values from cursor To get the values out of the cursor:  position the cursor at the correct row  use the get<type> methods to get the stored value Here’s an example: Using a While loop to iterate through the cursor to get the values moveToFirst() positions the cursor at the first record.
  • 22. The While loop will continue until the cursor passes the last record (when isAfterLast() is true). The getString() method is passed the column index. These indexes are determined by the position of the columns in our projection parameter. Very important You must close the cursor when you have finished using it to avoid memory leaks. Adding a row of data Adding a row is easy. Simply put all your data into a ContentValues object. Then pass the ContentValues object to the insert() method as a parameter. ContentValues objects stores the data in key/value pairs Insert the data into the database using the insert() method. You need three parameters:  the database table name  the nullColumnHack  the data in the form of a ContentValues object Pass the ContentValues object to the insert() method. The data is inserted into the database and the row ID returned NullColumnHack When inserting a new row. Always specify at least one column and corresponding value. If you have to add an empty row then you must pass the name of the column to set to null as the second parameter. An exception will be thrown if the nullColumnHack is set to null and you add an empty row. Set this parameter to NULL as long as you’re adding data to any of the columns. Updating rows It’s easy to update rows in the database. As with all queries or transactions, you must first get a database object. Then simply put the new data into a ContentValues object and use the WHERE clause to identify the rows that you want to update. In this example, I want to change the name from Reginald to Roland. I place the new name into the ContentValues object. Then I set up the WHERE clause:
  • 23. This will change all the names matching Reginald to Roland And put it all together in the update() method: Once updated, it returns the number of rows updated Important If you have an open cursor, then you need to run a new query so that it reflects the changes you made to the database by updating it. Deleting rows Use the delete() method to delete rows. Get a database object. Use the WHERE clause to identify which row or rows you want to delete then call delete(): Pass the table name, WHERE clause and its arguments to delete a row. It returns the number of records deleted Here’s an example of setting up the WHERE clause and its arguments to delete a specific row: Here we target a specific row by passing the row ID as the WHERE argument Important If you have an open cursor, then you need to run a new query so that it reflects the changes you made to the database by updating it. Where can I find the database file? You’ll find the database file in the /data/data/<package_name>/databases folder of your device but you won’t see it with a file browser unless the device is rooted. You will be able to access it if you’re using the emulator and Eclipse for example. You can of course copy the file over to another folder that you have access to.
  • 24. The Tutorial app Here’s a quick overview of the tutorial app which you can download: Pressing the Add Data button loads 5 records from a String array into the database. The row ID’s are displayed in the LogCat. Pressing Read Data displays all the rows in a list
  • 25. Pressing the MainActivity Read Data button starts a list activity and displays the data read from the database in a list
  • 26. These buttons are displayed in the activity started by pressing the More button in the MainActivity Pressing each of these buttons first loads a row of data in the database. This is purely for demonstration purposes to ensure that there is at least one row of data in the database.  Delete a record – deletes a single record identified by its row id. The number of rows deleted is displayed in the LogCat  Find a record – queries the database to find all rows where the NAME column value matches a given name. It returns a cursor which we loop through, displaying the rows in theLogCat  Update a record – updates all rows where the NAME column value matches a given name. The number of rows updated is displayed in the LogCat I hope that you have found this tutorial helpful. Have a look at the series of tutorials on Content Providers. Here's the first in the series, Android Content Providers. Importing Android Studio projects into eclipse
  • 27. You can’t import Android Studio projects into Eclipse. Here’s what you can do:  Create a new project in Eclipse  Either copy and paste the relevant files directly from Android Studio into Eclipse  Or create new files in Eclipse and then copy and paste the code from the Android Studio files into the new Eclipse files. Open the Android Studio files up in a text editor then copy and paste into the new Eclipse file
  • 28. The Android Studio file structure. The main folders are indicated by a yellow arrow Looking at an Android Studio project folder in Windows Explorer
  • 29. A typical Android Studio file structure as seen in Windows Explorer. We’re interested in the folder indicated by a yellow arrow Opening up the dialog_tutorial folder reveals the src folder. Opening this reveals the java and res folders. The res folder contains all the resources Opening up the dialog_tutorial folder reveals the src folder. This contains the:  java folder – containing the java class files (including the activities)  res folder – this is where you’ll find the layouts, drawables, menus and values files (strings, dimensions, colors)  AndroidManifest.xml – this is the manifest file
  • 30. Here’s a typical Eclipse project’s file structure: The folders indicated by a yellow arrow are the important ones Copying files directly Class files Copy the class files from Android Studio to Eclipse. You may need to change the package name when you’re done. Resource files Shouldn’t be a problem to copy these files directly over from Android Studio to Eclipse. AndroidManifest.xml Probably best to edit it rather than copy directly over. Open up the two manifest files (Android Studio and Eclipse) then copy and paste the code from the Android Studio manifest over to the Eclipse manifest.
  • 31. SQLiteDatabase is a class that allowed us to perform Create, Retrieve , Update, and Delete data (CRUD) operation. In this tutorial we will show you how to use SQLiteDatabase to perform CRUD operation in Android. Tool Used 1. Android Studio 0.40 To Do In this tutorial we will going to create an app that allow to Create, Retrieve, Update, and Delete, student record.. Easy? ya, is easy if you know how Download Code Android Studio SQLite Database Example Table Structure This is the Student table structure that going to use to store student detail information, we make thing simple so we only create 3 fields as image below Id is primary key and also auto increment number
  • 32. Screen Layout We will create 2 screens, first screen will display all students in the database which will look like this Second screen which is detail screen, when user click on the listview item it will bring user to new screen which will look like this
  • 33. Code The Layout 1. Let’s start to create a project and name it SQLiteDB, and the rest of step should be as standard, if you need guide on this step , please refer this link. These are the basic setting i’ve set. 2. In src > main > res > layout > activity_main.xml. Add ListView, Button into activity_main.xml and it will look like this. activity_main.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <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="com.instinctcoder.sqlitedb.MainActivity$PlaceholderFragment"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add" android:id="@+id/btnAdd"
  • 34. 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@android:id/list" android:layout_centerHorizontal="true" android:layout_alignParentTop="true" android:layout_above="@+id/btnAdd" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="List All" android:id="@+id/btnGetAll" android:layout_alignParentBottom="true" android:layout_toRightOf="@+id/btnAdd" /> </RelativeLayout> You need to change the ListView id to android:id=”@+id/list” if you choose to extends ListActivity in your class or else you will get error –> Your content must have a ListView whose id attribute is ‘android.R.id.list’ 3. Add another activity and we named it StudentDetail.java. The go to src > main > res > layout > activity_student_detail.xml. Add Button, TextView into activity_student_detail.xml and it will look like this. activity_student_detail.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 <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="com.instinctcoder.sqlitedb.StudentDetail$PlaceholderFragment"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
  • 35. 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 android:textAppearance="?android:attr/textAppearanceMedium" android:text="Name" android:id="@+id/textView" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="30dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Email" android:id="@+id/textView2" android:layout_below="@+id/textView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="29dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Age" android:id="@+id/textView3" android:layout_below="@+id/textView2" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="29dp" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPersonName" android:ems="10" android:id="@+id/editTextName" android:layout_above="@+id/textView2" android:layout_toRightOf="@+id/textView" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:ems="10" android:id="@+id/editTextEmail" android:layout_above="@+id/textView3" android:layout_toRightOf="@+id/textView" android:layout_alignRight="@+id/editTextName" android:layout_alignEnd="@+id/editTextName" /> <EditText
  • 36. 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="number" android:ems="10" android:id="@+id/editTextAge" android:layout_alignBottom="@+id/textView3" android:layout_alignLeft="@+id/editTextEmail" android:layout_alignStart="@+id/editTextEmail" android:layout_alignRight="@+id/editTextEmail" android:layout_alignEnd="@+id/editTextEmail" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save" android:id="@+id/btnSave" android:layout_alignParentBottom="true" android:layout_toLeftOf="@+id/btnClose" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Close" android:id="@+id/btnClose" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Delete" android:id="@+id/btnDelete" android:layout_alignTop="@+id/btnSave" android:layout_toLeftOf="@+id/btnSave" /> </RelativeLayout> 4. When user click on the list item we want to show student detail activity. So we need an unique id to retrieve student detail and this id must come from listview. To do this we have 2 options  The easiest way (if you like ;)) you could put id and name into listview item, and show it to the user (bad UI design -_-‘) and when user click at the code split the selected item and pass to student detail activity to retrieve the record. (i.e. ID_studentname will appear on the listview item)
  • 37.  Create a new simple layout to help us to retrieve student detail by student id and hide the student id in listview item from user. (I like this, or you should do this way :)). So to do with 2nd approach we need to create a new layout and name it view_student_entry.xml, and the code will look like below view_student_entry.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <?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"> <TextView android:id="@+id/student_Id" android:layout_width="fill_parent" android:layout_height="wrap_content" android:visibility="gone" /> <TextView android:id="@+id/student_name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="6dip" android:paddingTop="6dip" android:textSize="22sp" android:textStyle="bold" /> </LinearLayout> Code 1. Now let’s start code on table structure portion first – create table in Android. Base on the table structure image above, we will create a file name Student.java , and the code in this file will look like this Student.java 1 package com.instinctcoder.sqlitedb;
  • 38. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class Student { // Labels table name public static final String TABLE = "Student"; // Labels Table Columns names public static final String KEY_ID = "id"; public static final String KEY_name = "name"; public static final String KEY_email = "email"; public static final String KEY_age = "age"; // property help us to keep data public int student_ID; public String name; public String email; public int age; } 2. In order for us to create a table for need to use these classes SQLiteDatabase, SQLiteDatabase is the class for us to perform CRUD function, and SQLiteOpenHelper, SQLiteOpenHelper is a helper class to manage database creation and version management. We’ll create a class and name it DBHelper.java and code in this file will look like this, to ease on understand code line by line i put comment in code. DBHelper.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 package com.instinctcoder.sqlitedb; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { //version number to upgrade database version //each time if you Add, Edit table, you need to change the //version number. private static final int DATABASE_VERSION = 4; // Database Name private static final String DATABASE_NAME = "crud.db"; public DBHelper(Context context ) {
  • 39. 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { //All necessary tables you like to create will create here String CREATE_TABLE_STUDENT = "CREATE TABLE " + Student.TABLE + "(" + Student.KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + Student.KEY_name + " TEXT, " + Student.KEY_age + " INTEGER, " + Student.KEY_email + " TEXT )"; db.execSQL(CREATE_TABLE_STUDENT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed, all data will be gone!!! db.execSQL("DROP TABLE IF EXISTS " + Student.TABLE); // Create tables again onCreate(db); } } 3. With above 2 steps, student table will be created when app get started and now we could code the CRUD functions! Create StudentRepo.java, the purpose of this class is to perform CRUD on the Student table. The code in this file will look like this. StudentRepo.java 1 2 3 4 5 6 7 8 9 10 package com.instinctcoder.sqlitedb; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.HashMap; public class StudentRepo {
  • 40. 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 private DBHelper dbHelper; public StudentRepo(Context context) { dbHelper = new DBHelper(context); } public int insert(Student student) { //Open connection to write data SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(Student.KEY_age, student.age); values.put(Student.KEY_email,student.email); values.put(Student.KEY_name, student.name); // Inserting Row long student_Id = db.insert(Student.TABLE, null, values); db.close(); // Closing database connection return (int) student_Id; } public void delete(int student_Id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); // It's a good practice to use parameter ?, instead of concatenate string db.delete(Student.TABLE, Student.KEY_ID + "= ?", new String[] { String.valueOf(student_Id) }); db.close(); // Closing database connection } public void update(Student student) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(Student.KEY_age, student.age); values.put(Student.KEY_email,student.email); values.put(Student.KEY_name, student.name); // It's a good practice to use parameter ?, instead of concatenate string db.update(Student.TABLE, values, Student.KEY_ID + "= ?", new String[] { String.valueOf(student.student_ID) }); db.close(); // Closing database connection } public ArrayList<HashMap<String, String>> getStudentList() { //Open connection to read only SQLiteDatabase db = dbHelper.getReadableDatabase(); String selectQuery = "SELECT " + Student.KEY_ID + "," + Student.KEY_name + "," + Student.KEY_email + "," + Student.KEY_age + " FROM " + Student.TABLE;
  • 41. 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 //Student student = new Student(); ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { HashMap<String, String> student = new HashMap<String, String>(); student.put("id", cursor.getString(cursor.getColumnIndex(Student.KEY_ID))); student.put("name", cursor.getString(cursor.getColumnIndex(Student.KEY_name))); studentList.add(student); } while (cursor.moveToNext()); } cursor.close(); db.close(); return studentList; } public Student getStudentById(int Id){ SQLiteDatabase db = dbHelper.getReadableDatabase(); String selectQuery = "SELECT " + Student.KEY_ID + "," + Student.KEY_name + "," + Student.KEY_email + "," + Student.KEY_age + " FROM " + Student.TABLE + " WHERE " + Student.KEY_ID + "=?";// It's a good practice to use parameter ?, instead of concatenate string int iCount =0; Student student = new Student(); Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(Id) } ); if (cursor.moveToFirst()) { do { student.student_ID =cursor.getInt(cursor.getColumnIndex(Student.KEY_ID)); student.name =cursor.getString(cursor.getColumnIndex(Student.KEY_name)); student.email =cursor.getString(cursor.getColumnIndex(Student.KEY_email)); student.age =cursor.getInt(cursor.getColumnIndex(Student.KEY_age)); } while (cursor.moveToNext()); } cursor.close(); db.close(); return student; }
  • 42. 117 } 4. When user click on the listview item we will display student detail information on detail screen, we will have this code to do the job for us. Go to src > main > java > StudentDetail.java. and copy this code into the class. StudentDetail.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 package com.instinctcoder.sqlitedb; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class StudentDetail extends ActionBarActivity implements android.view.View.OnClickListener{ Button btnSave , btnDelete; Button btnClose; EditText editTextName; EditText editTextEmail; EditText editTextAge; private int _Student_Id=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_student_detail); btnSave = (Button) findViewById(R.id.btnSave); btnDelete = (Button) findViewById(R.id.btnDelete); btnClose = (Button) findViewById(R.id.btnClose);
  • 43. 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 editTextName = (EditText) findViewById(R.id.editTextName); editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextAge = (EditText) findViewById(R.id.editTextAge); btnSave.setOnClickListener(this); btnDelete.setOnClickListener(this); btnClose.setOnClickListener(this); _Student_Id =0; Intent intent = getIntent(); _Student_Id =intent.getIntExtra("student_Id", 0); StudentRepo repo = new StudentRepo(this); Student student = new Student(); student = repo.getStudentById(_Student_Id); editTextAge.setText(String.valueOf(student.age)); editTextName.setText(student.name); editTextEmail.setText(student.email); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.student_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void onClick(View view) { if (view == findViewById(R.id.btnSave)){ StudentRepo repo = new StudentRepo(this); Student student = new Student(); student.age= Integer.parseInt(editTextAge.getText().toString()); student.email=editTextEmail.getText().toString(); student.name=editTextName.getText().toString(); student.student_ID=_Student_Id; if (_Student_Id==0){
  • 44. 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 _Student_Id = repo.insert(student); Toast.makeText(this,"New Student Insert",Toast.LENGTH_SHORT).show(); }else{ repo.update(student); Toast.makeText(this,"Student Record updated",Toast.LENGTH_SHORT).show(); } }else if (view== findViewById(R.id.btnDelete)){ StudentRepo repo = new StudentRepo(this); repo.delete(_Student_Id); Toast.makeText(this, "Student Record Deleted", Toast.LENGTH_SHORT); finish(); }else if (view== findViewById(R.id.btnClose)){ finish(); } } } 5. We have almost all pieces in place to display data for us in listview. So we continue in MainActivity.java, paste this code into file. MainActivity.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package com.instinctcoder.sqlitedb; import android.app.ListActivity; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast;
  • 45. 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends ListActivity implements android.view.View.OnClickListener{ Button btnAdd,btnGetAll; TextView student_Id; @Override public void onClick(View view) { if (view== findViewById(R.id.btnAdd)){ Intent intent = new Intent(this,StudentDetail.class); intent.putExtra("student_Id",0); startActivity(intent); }else { StudentRepo repo = new StudentRepo(this); ArrayList<HashMap<String, String>> studentList = repo.getStudentList(); if(studentList.size()!=0) { ListView lv = getListView(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view,int position, long id) { student_Id = (TextView) view.findViewById(R.id.student_Id); String studentId = student_Id.getText().toString(); Intent objIndent = new Intent(getApplicationContext(),StudentDetail.class); objIndent.putExtra("student_Id", Integer.parseInt( studentId)); startActivity(objIndent); } }); ListAdapter adapter = new SimpleAdapter( MainActivity.this,studentList, R.layout.view_student_entry, new String[] { "id","name"}, new int[] {R.id.student_Id, R.id.student_name}); setListAdapter(adapter); }else{ Toast.makeText(this,"No student!",Toast.LENGTH_SHORT).show(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnAdd = (Button) findViewById(R.id.btnAdd); btnAdd.setOnClickListener(this);
  • 46. 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 btnGetAll = (Button) findViewById(R.id.btnGetAll); btnGetAll.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
  • 47. 6. That’s all, Run! You should see the below result.
  • 48. If everything go smooth, database will be created in this path “data > data > SQLiteDB > databases > crud.db”, if you like to browse data and table structure of the database you could refer to How to browse Android Emulator SQLite Database What’s next? So far we have showed you how to CRUD data locally without needed access internet, the next post we will show you how to pass data back to server and save in the SQL Server, How to Call ASP.Net Web API from Android Studio. Updated on 18 Mar 2015 This step is optional and only for those who are using eclipse I noticed some reader had stuck in the StudentDetail.java file when they use Eclipse to try out this tutorial, the reason why you click “Add” and failed is
  • 49. because you need to import android-support-v4.jar and android-support-v7- appcompat.jar into your workspace, the detail you could follow this link Alternatively, you use the this source code which build in Eclipse IDE 23.0.2.1259578 and the only different with the Android Studio version is below code StudentDetail.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package com.instinctcoder.sqlitedb; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class StudentDetail extends Activity implements android.view.View.OnClickListener{ Button btnSave , btnDelete; Button btnClose; EditText editTextName; EditText editTextEmail; EditText editTextAge; private int _Student_Id=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_student_detail); btnSave = (Button) findViewById(R.id.btnSave); btnDelete = (Button) findViewById(R.id.btnDelete); btnClose = (Button) findViewById(R.id.btnClose); editTextName = (EditText) findViewById(R.id.editTextName); editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextAge = (EditText) findViewById(R.id.editTextAge); btnSave.setOnClickListener(this); btnDelete.setOnClickListener(this); btnClose.setOnClickListener(this);
  • 50. 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 _Student_Id =0; Intent intent = getIntent(); _Student_Id =intent.getIntExtra("student_Id", 0); StudentRepo repo = new StudentRepo(this); Student student = new Student(); student = repo.getStudentById(_Student_Id); editTextAge.setText(String.valueOf(student.age)); editTextName.setText(student.name); editTextEmail.setText(student.email); } @Override public void onClick(View view) { // TODO Auto-generated method stub if (view == findViewById(R.id.btnSave)){ StudentRepo repo = new StudentRepo(this); Student student = new Student(); student.age= Integer.parseInt(editTextAge.getText().toString()); student.email=editTextEmail.getText().toString(); student.name=editTextName.getText().toString(); student.student_ID=_Student_Id; if (_Student_Id==0){ _Student_Id = repo.insert(student); Toast.makeText(this,"New Student Insert",Toast.LENGTH_SHORT).show(); }else{ repo.update(student); Toast.makeText(this,"Student Record updated",Toast.LENGTH_SHORT).show(); } }else if (view== findViewById(R.id.btnDelete)){ StudentRepo repo = new StudentRepo(this); repo.delete(_Student_Id); Toast.makeText(this, "Student Record Deleted", Toast.LENGTH_SHORT); finish(); }else if (view== findViewById(R.id.btnClose)){ finish(); } } }
  • 51. In this tutorial I will show how to use a database in Android by creating the tables and columns using the SQLite Database Browser.1. So the first step is to download the SQLite Database Browser2. Make a new project and name the main java class that generates with the project “MyActivity”. 3. Now you have to go to the SQLite Database Browser that you have just downloaded and run it. Here you have to create the tables, the columns etc. I will show you how in the following lines, so pay attention  Create a newdatabase To create a new database go to File – New Database and click it. Now you will have to name your database as “database” and save it in your project in the folder “assets”. To do this navigate to where your project is created, open the folder assets, then in the File Name field enter the name “database” and press the Save button.  Populate the database
  • 52. Before to create the tables for your project, you have to create a specific table called “android_metadata” with a column called “locale” and a record called “en_US”. If we don’t create this table you will get a force close. To add the column “locale”press on the Add button like in the picture bellow. Now enter the name of the column and the type like in the picture bellow: The column is created now, so the last thing you have to do is to confirm the creation of the table by pressing on the Createlike in the picture bellow:
  • 53. Now that the table and the column are created you have to enter the record “en_US”. Go to “Browse Data” and press on theNew Record button. An empty record will be added so you will have to edit it by double clicking on it. A new window will appear and in that window you must put “en_US” text.
  • 54. And finally we can create our own tables. You must create a table called “People”, with 2 columns: one called “Name” and the other one called “_id” . Technically the field _id is not required, however if you will use of the CursorAdapter class then you it is required .To create a new table follow the steps from the picture bellow: Now you must add the column “_id” too so press the Add button and enter the information like in the picture:
  • 55. NOTE: Don’t forget to SAVE the database changes. 4. Now we have to start coding.  First you have to create a new class called “ApplicationContextProvider” which will provide the context wherever in the application. The code looks like this: Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import android.app.Application; import android.content.Context; public class ApplicationContextProvider extends Application { /** * Keeps a reference of the application context */ privatestatic Context sContext; @Override public void onCreate() { super.onCreate(); sContext = getApplicationContext(); } /** * Returns the application context * * @return application context */ public staticContext getContext() { return sContext; } } Now you have to declare this class in the AndroidManifest.xml in the application tag: XHTML
  • 56. 1 2 <application android:name=".ApplicationContextProvider" android:label="@string/app_name">  Create a new class for database code, called “DataBaseManager”. The code looks like this: Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class DataBaseManager extends SQLiteOpenHelper { // TheAndroid's default systempath of your application database. //data/data/ and /databases remain the same always. The one that must be changed is com.example which represents //the MAIN package of your project privatestatic String DB_PATH = "/data/data/com.example/databases/"; //the name of your database privatestatic String DB_NAME = "database"; privatestatic SQLiteDatabase mDataBase;
  • 57. 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 privatestatic DataBaseManager sInstance = null; // database version privatestatic final int DATABASE_VERSION = 1; /** * Constructor Takes and keeps a reference of the passed context in order to * access to the application assets and resources. */ privateDataBaseManager() { super(ApplicationContextProvider.getContext(), DB_NAME, null, DATABASE_VERSION); try { createDataBase(); openDataBase(); } catch (IOException e) { e.printStackTrace(); } } /** * Singleton for DataBase * * @return singleton instance */ public staticDataBaseManager instance() { if (sInstance == null) { sInstance = new DataBaseManager(); } return sInstance; } /** * Creates a empty database on thesystemand rewrites it with your own * database. * * @throws java.io.IOException io exception */ privatevoid createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist } else { // By calling this method an empty databasewill be created into // thedefault systempath // of your application so we are gonna be able to overwrite that // database with our database. this.getReadableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error("Error copyingdatabase");
  • 58. 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 } } } /** * Check if the database already exist to avoid re-copying the file each * time you open theapplication. * * @return trueif it exists, false if it doesn't */ privateboolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { // database doesn't exist yet. } if (checkDB != null) { checkDB.close(); } return checkDB != null; } /** * Copies your database from your local assets-folder to the just created * empty databasein thesystemfolder, from where it can be accessed and * handled. This is done by transfering bytestream. * * @throws java.io.IOException io exception */ public void copyDataBase() throws IOException { // Open your local db as the input stream InputStreammyInput = ApplicationContextProvider.getContext().getAssets().open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH + DB_NAME; // Open theempty db as the output stream OutputStream myOutput= new FileOutputStream(outFileName); // transfer bytes from the inputfileto theoutputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close();
  • 59. 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 myInput.close(); } privatevoid openDataBase() throws SQLException { // Open thedatabase String myPath = DB_PATH + DB_NAME; mDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); } /** * Select method * * @param query select query * @return - Cursor with theresults * @throws android.database.SQLException sql exception */ public Cursor select(String query) throws SQLException { return mDataBase.rawQuery(query, null); } /** * Insert method * * @param table - name of the table * @param values values to insert * @throws android.database.SQLException sql exception */ public void insert(String table, ContentValues values) throws SQLException { mDataBase.insert(table, null, values); } /** * Delete method * * @param table - table name * @param where WHERE clause, if pass null, all therows will be deleted * @throws android.database.SQLException sql exception */ public void delete(String table, String where) throws SQLException { mDataBase.delete(table, where, null); } /** * Updatemethod * * @param table - table name * @param values - values to update * @param where - WHERE clause, if pass null, all rows will be updated */ public void update(String table, ContentValues values, String where) { mDataBase.update(table, values, where, null); } /** * Let you make a raw query
  • 60. 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 * * @param command - the sql comand you want to run */ public void sqlCommand(String command) { mDataBase.execSQL(command); } @Override public synchronized void close() { if (mDataBase != null) mDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } Now please pay attention at private static String DB_PATH = “/data/data/com.example/databases/”; and private static String DB_NAME = “database”; This two variable must be changed depending of your project. DB_PATH general code looks like this: Java 1 privatestatic String DB_PATH = "/data/data/YOUR_MAIN_PACKAGE/databases/"; But what “MAIN_PACKAGE” means? For example let’s imagine that we have a main package called “com.example” and inside this package we have another package called “com.example.utils”. If the DataBaseManager is situated in the “com.example.utils” package the DB_PATH will be: Java 1 privatestatic String DB_PATH = "/data/data/com.example/databases/"; and NOT: Java
  • 61. 1 privatestatic String DB_PATH = "/data/data/com.example.utils/databases/"; And DB_NAME general code looks like this: Java 1 privatestatic String DB_NAME = "YOUR_DATABASE_NAME";  Now go to “res – layout – main.xml” and put the following code. We create a text view to see the names and 3 buttons for: Insert, Update and Delete. XHTML 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: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:id="@+id/name_1"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/insert" android:text="INSERT"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/update" android:text="UPDATE"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/delete" android:text="DELETE"/> </LinearLayout>  Now go to the “MyActivity” class and put this code: Java
  • 62. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MyActivity extends Activity { privateDataBaseManager dataBase; privateButton insertButton; privateButton updateButton; privateButton deleteButton; privateTextView textView; //put the table name and column in constants public staticfinal String TABLE_NAME = "People"; public staticfinal String COLUMN_NAME = "name"; /** Called when theactivity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //creates and open thedatabase so we can use it dataBase = DataBaseManager.instance(); textView = (TextView)findViewById(R.id.name_1); insertButton = (Button)findViewById(R.id.insert); updateButton = (Button)findViewById(R.id.update); deleteButton = (Button)findViewById(R.id.delete); insertButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //with ContentValues put thedata we want into the database ContentValues values = new ContentValues(); values.put(COLUMN_NAME, "Diana"); //here we insert the data we have put in values dataBase.insert(TABLE_NAME, values); updateTextView(); } }); updateButton.setOnClickListener(new View.OnClickListener() {
  • 63. 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 @Override public void onClick(View view) { //with ContentValues put thedata we want into the database ContentValues values = new ContentValues(); values.put(COLUMN_NAME,"George"); //here we replace the record which has the_id=1 with thegiven name in thevalues "George" dataBase.update(TABLE_NAME, values, "_id=1"); updateTextView(); } }); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //here we delete the record which has the"name=George" dataBase.delete(TABLE_NAME,"name='George'"); updateTextView(); } }); } public void updateTextView(){ //to get data from database we need a cursor. //after we performa select query all the data from database specific for the query, will be in the cursor // "*" means "all" in translation the query means "SELECT ALL FROM NAMETABLE" Cursor cursor = dataBase.select("SELECT * FROM " + TABLE_NAME); textView.setText(""); //the cursor iterates the column "name" while (cursor.moveToNext()){ //in this string we get the record for each row from thecolumn "name" String s = cursor.getString(cursor.getColumnIndex(COLUMN_NAME)); //in this textView will be added, updated or deleted thestring // "n" means "new line" textView.append("n" + s); } //here we close the cursor because we do not longer need it cursor.close(); } } So, as you can see you can perform the following action on the database: INSERT, UPDATE, DELETE and SELECT. The general code for INSERT into database is: Java
  • 64. 1 2 3 ContentValues values = new ContentValues(); values.put(COLUMN_NAME, "WHAT YOU WANT TO INSERT"); dataBase.insert(TABLE_NAME, values); The general code for UPDATE something from database is: Java 1 2 3 ContentValues values = new ContentValues(); values.put(COLUMN_NAME,"VALUE WITH WHICH YOU WANT TO UPDATE"); dataBase.update(TABLE_NAME, values, WHERE CLAUSE like "id='1'" or name="sam" etc); The general code for DELETE something from database is: Java 1 dataBase.delete(TABLE_NAME,WHERE CLAUSE like "name='George'"); The general code for SELECT something from database is: NOTE: If you make any changes to the database (create a newtable, or a newcolumn etc) you must uninstall your project from emulator or test device and run again your project. You have to do this because the previous database doesn’t update “in real time” with changes you make on it’s structure. Now you can test the application INSERT UPDATE
  • 66. SQLite is a opensource 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 Database - Package The main package is android.database.sqlite that contains the classes to manage your own databases Database - Creation In order to create a database you just need to call this method openOrCreateDatabase 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
  • 67. SQLiteDatabse mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null); 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, SQLiteDatabase.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() Database - Insertion we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax is given below
  • 68. 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(1); String password = resultSet.getString(2); 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
  • 69. the name of the 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) {}
  • 70. } 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. s Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs. 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
  • 71. 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; 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;
  • 72. 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); } });
  • 73. } @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);
  • 74. } } Following is the modified content of display contact activityDisplayContact.java package com.example.addressbook; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; 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;
  • 75. @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)); String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY)); if (!rs.isClosed()) { rs.close();
  • 76. } 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)
  • 77. { int Value = extras.getInt("id"); if(Value>0){ getMenuInflater().inflate(R.menu.display_contact, menu); } else{ getMenuInflater().inflate(R.menu.main, menu); } } return true; } 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);
  • 78. 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 } }); AlertDialog d = builder.create(); d.setTitle("Are you sure"); d.show(); return true; default:
  • 79. 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);
  • 80. startActivity(intent); } } } } Following is the content of Database class DBHelper.java package com.example.addressbook; 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) {
  • 81. 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) { 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; }
  • 82. 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) }); }
  • 83. public ArrayList<String> getAllCotacts() { ArrayList<String> array_list = new ArrayList<String>(); //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 <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"
  • 84. 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" 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
  • 85. 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 <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"> <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"
  • 86. 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" />
  • 87. <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" 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"
  • 88. 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 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"
  • 89. 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 <?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"
  • 90. android:title="@string/Add_New" > </item> </menu> Following is the content of the res/menu/display_contact.xml <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" >
  • 91. <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".DisplayContact"/> </application> </manifest> Creating a SQLite database app Create a new Android mobile application solution in Xamarin Studio If you don't have Xamarin Studio, don't worry. You can download it here: Xamarin Studio Database class 1. Right click project BD_Demo --> Add --> New File… --> Android Class (Database)
  • 92. Database class is for handling SQLiteDatabase object. We are now going to create objects and methods for handling CRUD (Create, Read, Update and Delete) operations in a database table. Here is the code: //Required assemblies using Android.Database.Sqlite; using System.IO; namespace BD_Demo { class Database { //SQLiteDatabase object for database handling private SQLiteDatabase sqldb; //String for Query handling private string sqldb_query; //String for Message handling
  • 93. private string sqldb_message; //Bool to check for database availability private bool sqldb_available; //Zero argument constructor, initializes a new instance of Database class public Database() { sqldb_message = ""; sqldb_available = false; } //One argument constructor, initializes a new instance of Database class with database name parameter public Database(string sqldb_name) { try { sqldb_message = ""; sqldb_available = false; CreateDatabase(sqldb_name); } catch (SQLiteException ex) { sqldb_message = ex.Message; } } //Gets or sets value depending on database availability public bool DatabaseAvailable { get{ return sqldb_available; }