SlideShare a Scribd company logo
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; }
set{ sqldb_available = value; }
}
//Gets or sets the value for message handling
public string Message
{
get{ return sqldb_message; }
set{ sqldb_message = value; }
}
//Creates a new database which name is given by the parameter
public void CreateDatabase(string sqldb_name)
{
try
{
sqldb_message = "";
string sqldb_location = System.Environment.GetFolderPath(System.
Environment.SpecialFolder.Personal);
string sqldb_path = Path.Combine(sqldb_location, sqldb_name);
bool sqldb_exists = File.Exists(sqldb_path);
if(!sqldb_exists)
{
sqldb = SQLiteDatabase.OpenOrCreateDatabase(sqldb_path,null
);
sqldb_query = "CREATE TABLE IF NOT EXISTS MyTable (_id I
NTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR, LastName
VARCHAR, Age INT);";
sqldb.ExecSQL(sqldb_query);
sqldb_message = "Database: " + sqldb_name + " created";
}
else
{
sqldb = SQLiteDatabase.OpenDatabase(sqldb_path, null, Databa
seOpenFlags.OpenReadwrite);
sqldb_message = "Database: " + sqldb_name + " opened";
}
sqldb_available=true;
}
catch(SQLiteException ex)
{
sqldb_message = ex.Message;
}
}
//Adds a new record with the given parameters
public void AddRecord(string sName, string sLastName, int iAge)
{
try
{
sqldb_query = "INSERT INTO MyTable (Name, LastName, Age) VA
LUES ('" + sName + "','" + sLastName + "'," + iAge + ");";
sqldb.ExecSQL(sqldb_query);
sqldb_message = "Record saved";
}
catch(SQLiteException ex)
{
sqldb_message = ex.Message;
}
}
//Updates an existing record with the given parameters depending on id p
arameter
public void UpdateRecord(int iId, string sName, string sLastName, int iAg
e)
{
try
{
sqldb_query="UPDATE MyTable SET Name ='" + sName + "', Last
Name ='" + sLastName + "', Age ='" + iAge + "' WHERE _id ='" + iId + "';";
sqldb.ExecSQL(sqldb_query);
sqldb_message = "Record " + iId + " updated";
}
catch(SQLiteException ex)
{
sqldb_message = ex.Message;
}
}
//Deletes the record associated to id parameter
public void DeleteRecord(int iId)
{
try
{
sqldb_query = "DELETE FROM MyTable WHERE _id ='" + iId + "';";
sqldb.ExecSQL(sqldb_query);
sqldb_message = "Record " + iId + " deleted";
}
catch(SQLiteException ex)
{
sqldb_message = ex.Message;
}
}
//Searches a record and returns an Android.Database.ICursor cursor
//Shows all the records from the table
public Android.Database.ICursor GetRecordCursor()
{
Android.Database.ICursor sqldb_cursor = null;
try
{
sqldb_query = "SELECT*FROM MyTable;";
sqldb_cursor = sqldb.RawQuery(sqldb_query, null);
if(!(sqldb_cursor != null))
{
sqldb_message = "Record not found";
}
}
catch(SQLiteException ex)
{
sqldb_message = ex.Message;
}
return sqldb_cursor;
}
//Searches a record and returns an Android.Database.ICursor cursor
//Shows records according to search criteria
public Android.Database.ICursor GetRecordCursor(string sColumn, strin
g sValue)
{
Android.Database.ICursor sqldb_cursor = null;
try
{
sqldb_query = "SELECT*FROM MyTable WHERE " + sColumn + "
LIKE '" + sValue + "%';";
sqldb_cursor = sqldb.RawQuery(sqldb_query, null);
if(!(sqldb_cursor != null))
{
sqldb_message = "Record not found";
}
}
catch(SQLiteException ex)
{
sqldb_message = ex.Message;
}
return sqldb_cursor;
}
}
}
Records Layout
2. Expand Resources Folder on Solution Pad
a) Right click Layout Folder --> Add --> New File… --> Android Layout
(record_view)
We need a layout for each item we are going to add to our database table. We
do not need to define a layout for every item and this same layout can be re-
used as many times as the items we have.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="ID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Id_row"
android:layout_weight="1"
android:gravity="center"
android:textSize="15dp"
android:textColor="#ffffffff"
android:textStyle="bold" />
<TextView
android:text="Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Name_row"
android:layout_weight="1"
android:textSize="15dp"
android:textColor="#ffffffff"
android:textStyle="bold" />
<TextView
android:text="LastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/LastName_row"
android:layout_weight="1"
android:textSize="15dp"
android:textStyle="bold"
android:textColor="#ffffffff" />
<TextView
android:text="Age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Age_row"
android:layout_weight="1"
android:textSize="15dp"
android:textStyle="bold"
android:textColor="#ffffffff"
android:gravity="center" />
</LinearLayout>
Main Layout
3. Expand Resources folder on Solution Pad --> Expand Layout folder
a) Double Click Main layout (Main.axml)
Xamarin automatically makes Form Widgets's IDs available by referencing
Resorce.Id class.
Images
add.png delete.png save.png search.png
Note: I highly recommended putting images into Drawable folder.
-Expand Resources Folder
~Right Click Drawable folder --> Add --> Add Files…
<?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">
<LinearLayout
android:orientation="horizontal"
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff004150">
<TextView
android:text="Name"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffffff" />
<TextView
android:text="Last Name"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textSize="20dp"
android:textColor="#ffffffff"
android:textStyle="bold" />
<TextView
android:text="Age"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffffff" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff004185">
<EditText
android:inputType="textPersonName"
android:id="@+id/txtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<EditText
android:id="@+id/txtLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<EditText
android:inputType="number"
android:id="@+id/txtAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:background="#ff004185"
android:gravity="center">
<ImageButton
android:layout_width="50dp"
android:paddingLeft="10dp"
android:layout_height="50dp"
android:background="@drawable/add"
android:id="@+id/imgAdd"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp" />
<ImageButton
android:layout_width="50dp"
android:paddingLeft="10dp"
android:layout_height="50dp"
android:background="@drawable/save"
android:id="@+id/imgEdit"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" />
<ImageButton
android:layout_width="50dp"
android:paddingLeft="10dp"
android:layout_height="50dp"
android:background="@drawable/delete"
android:id="@+id/imgDelete"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" />
<ImageButton
android:layout_width="50dp"
android:paddingLeft="10dp"
android:layout_height="50dp"
android:background="@drawable/search"
android:id="@+id/imgSearch"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" />
</LinearLayout>
<TextView
android:text="Message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/shMsg"
android:background="#ff004185"
android:textColor="#ffffffff"
android:textStyle="bold"
android:textSize="15dp"
android:gravity="center" />
<LinearLayout
android:orientation="horizontal"
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:background="#ff004150"
android:gravity="center">
<TextView
android:text="ID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="20dp"
android:layout_weight="1"
android:gravity="center"
android:id="@+id/id" />
<TextView
android:text="Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:gravity="center"
android:textSize="20dp"
android:layout_weight="1"
android:id="@+id/name" />
<TextView
android:text="Last Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:layout_weight="1"
android:gravity="center"
android:textSize="20dp"
android:id="@+id/last" />
<TextView
android:text="Age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:layout_weight="1"
android:textSize="20dp"
android:gravity="center"
android:id="@+id/age" />
</LinearLayout>
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:id="@+id/listItems" />
</LinearLayout>
Main Activity class
4. Double Click Main Activity (MainActivity.cs)
We have to get object instances from main layout and provide them with an
event. Main events will be Add, Edit, Delete and Search for the image buttons
we have defined. We have to populate our ListView object with the data
stored in the database or create a new one in case it does not exist.
namespace BD_Demo
{
//Main activity for app launching
[Activity (Label = "BD_Demo", MainLauncher = true)]
public class MainActivity : Activity
{
//Database class new object
Database sqldb;
//Name, LastName and Age EditText objects for data input
EditText txtName, txtAge, txtLastName;
//Message TextView object for displaying data
TextView shMsg;
//Add, Edit, Delete and Search ImageButton objects for events handling
ImageButton imgAdd, imgEdit, imgDelete, imgSearch;
//ListView object for displaying data from database
ListView listItems;
//Launches the Create event for app
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
//Set our Main layout as default view
SetContentView (Resource.Layout.Main);
//Initializes new Database class object
sqldb = new Database("person_db");
//Gets ImageButton object instances
imgAdd = FindViewById<ImageButton> (Resource.Id.imgAdd);
imgDelete = FindViewById<ImageButton> (Resource.Id.imgDelete);
imgEdit = FindViewById<ImageButton> (Resource.Id.imgEdit);
imgSearch = FindViewById<ImageButton> (Resource.Id.imgSearch);
//Gets EditText object instances
txtAge = FindViewById<EditText> (Resource.Id.txtAge);
txtLastName = FindViewById<EditText> (Resource.Id.txtLastName);
txtName = FindViewById<EditText> (Resource.Id.txtName);
//Gets TextView object instances
shMsg = FindViewById<TextView> (Resource.Id.shMsg);
//Gets ListView object instance
listItems = FindViewById<ListView> (Resource.Id.listItems);
//Sets Database class message property to shMsg TextView instance
shMsg.Text = sqldb.Message;
//Creates ImageButton click event for imgAdd, imgEdit, imgDelete and
imgSearch
imgAdd.Click += delegate {
//Calls function AddRecord for adding a new record
sqldb.AddRecord (txtName.Text, txtLastName.Text, int.Parse (txtAg
e.Text));
shMsg.Text = sqldb.Message;
txtName.Text = txtAge.Text = txtLastName.Text = "";
GetCursorView();
};
imgEdit.Click += delegate {
int iId = int.Parse(shMsg.Text);
//Calls UpdateRecord function for updating an existing record
sqldb.UpdateRecord (iId, txtName.Text, txtLastName.Text, int.Parse
(txtAge.Text));
shMsg.Text = sqldb.Message;
txtName.Text = txtAge.Text = txtLastName.Text = "";
GetCursorView();
};
imgDelete.Click += delegate {
int iId = int.Parse(shMsg.Text);
//Calls DeleteRecord function for deleting the record associated to id
parameter
sqldb.DeleteRecord (iId);
shMsg.Text = sqldb.Message;
txtName.Text = txtAge.Text = txtLastName.Text = "";
GetCursorView();
};
imgSearch.Click += delegate {
//Calls GetCursorView function for searching all records or single re
cord according to search criteria
string sqldb_column = "";
if (txtName.Text.Trim () != "")
{
sqldb_column = "Name";
GetCursorView (sqldb_column, txtName.Text.Trim ());
} else
if (txtLastName.Text.Trim () != "")
{
sqldb_column = "LastName";
GetCursorView (sqldb_column, txtLastName.Text.Trim ());
} else
if (txtAge.Text.Trim () != "")
{
sqldb_column = "Age";
GetCursorView (sqldb_column, txtAge.Text.Trim ());
} else
{
GetCursorView ();
sqldb_column = "All";
}
shMsg.Text = "Search " + sqldb_column + ".";
};
//Add ItemClick event handler to ListView instance
listItems.ItemClick += new EventHandler<AdapterView.ItemClickEvent
Args> (item_Clicked);
}
//Launched when a ListView item is clicked
void item_Clicked (object sender, AdapterView.ItemClickEventArgs e)
{
//Gets TextView object instance from record_view layout
TextView shId = e.View.FindViewById<TextView> (Resource.Id.Id_ro
w);
TextView shName = e.View.FindViewById<TextView> (Resource.Id.N
ame_row);
TextView shLastName = e.View.FindViewById<TextView> (Resource.I
d.LastName_row);
TextView shAge = e.View.FindViewById<TextView> (Resource.Id.Age
_row);
//Reads values and sets to EditText object instances
txtName.Text = shName.Text;
txtLastName.Text = shLastName.Text;
txtAge.Text = shAge.Text;
//Displays messages for CRUD operations
shMsg.Text = shId.Text;
}
//Gets the cursor view to show all records
void GetCursorView()
{
Android.Database.ICursor sqldb_cursor = sqldb.GetRecordCursor ();
if (sqldb_cursor != null)
{
sqldb_cursor.MoveToFirst ();
string[] from = new string[] {"_id","Name","LastName","Age" };
int[] to = new int[] {
Resource.Id.Id_row,
Resource.Id.Name_row,
Resource.Id.LastName_row,
Resource.Id.Age_row
};
//Creates a SimplecursorAdapter for ListView object
SimpleCursorAdapter sqldb_adapter = new SimpleCursorAdapter (t
his, Resource.Layout.record_view, sqldb_cursor, from, to);
listItems.Adapter = sqldb_adapter;
}
else
{
shMsg.Text = sqldb.Message;
}
}
//Gets the cursor view to show records according to search criteria
void GetCursorView (string sqldb_column, string sqldb_value)
{
Android.Database.ICursor sqldb_cursor = sqldb.GetRecordCursor (sql
db_column, sqldb_value);
if (sqldb_cursor != null)
{
sqldb_cursor.MoveToFirst ();
string[] from = new string[] {"_id","Name","LastName","Age" };
int[] to = new int[]
{
Resource.Id.Id_row,
Resource.Id.Name_row,
Resource.Id.LastName_row,
Resource.Id.Age_row
};
SimpleCursorAdapter sqldb_adapter = new SimpleCursorAdapter (t
his, Resource.Layout.record_view, sqldb_cursor, from, to);
listItems.Adapter = sqldb_adapter;
}
else
{
shMsg.Text = sqldb.Message;
}
}
}
}
5. Build solution and run
Ok, so that's it for today! I hope that this tutorial has been useful. Feel free to
make any questions, complaints, suggestions or comments.
Happy coding!
How to Check Database Using SQLite Manager in
Android
By Sazid Mauhammad on Feb 26, 2013
In this article I tell you how to see your SQLite database, if you want to see the details, using SQLite
Manager.
 21.8k
 1
 1
 facebook
 twitter
 linkedIn
 google Plus

o
o
o
o
o
o
o
o
o
o
o
o
o
 expand
Download Aspose, it really helps
Introduction
In this article I tell you how to see your SQLite database, if you want to see the details. You can see your
SQLite database in three ways.
1. Using a command prompt in window.
2. Using coding, to see details you can get using code in your project.
3. Using SQLite manager.
Here I explain how to use SQLIte manager. To see details of your database you must use the following
procedure.
Step 1
First, open any web browser and add to it the SQLite Manager add-on as shown in the following image.
Step 2
Now create a project to save your database using SQLite database as I did in my last article Create
Database in Android.
Step 3
Open DDMS Perspective in your Eclipse editor and go to the File Explorer and select "Data" -> "Data"
then enter your project package name ( in my case its "com.db.documents" ) as shown in the following
image:
Step 4
Now pull outside selective database from your device using the pull button and save the database with a
".db"extension as shown in the following image:
Save it as "database.db":
Step 5
Now open your browser and open SQLite Manager using "Tool" -> "SQLIte Manager" as shown in the
following image:
Steps 6
Connect to your database as shown in the following image:
Step 7
And at last you will see the new database in your project as shown below:

More Related Content

PDF
Hands-On Lab Data Transformation Services - SQL Server
DOC
ssis lab
DOCX
Android sq lite-chapter 22
PDF
Android sq lite database tutorial
PPTX
Metaworks3
PPTX
Databases and SQL - Lecture C
DOC
Cis407 a ilab 3 web application development devry university
PPTX
Android Database Tutorial
Hands-On Lab Data Transformation Services - SQL Server
ssis lab
Android sq lite-chapter 22
Android sq lite database tutorial
Metaworks3
Databases and SQL - Lecture C
Cis407 a ilab 3 web application development devry university
Android Database Tutorial

What's hot (19)

PPT
A pain free migraine
PDF
Session06 handling xml data
PDF
CaseStudy-MohammedImranAlam-Xcelsius
PPT
Visualizing STEP Files
PPTX
Disconnected data
PPTX
Ado.net
PPS
Ado.net session05
DOCX
Prg421
DOCX
Exercises
PPS
Ado.net session02
PPTX
ADO.NET by ASP.NET Development Company in india
PDF
Chapter6 database connectivity
PDF
Laboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y Salto
PPS
11 qmds2005 session16
PPS
Ado.net session04
PDF
Hibernate II
PPT
ASP.NET 09 - ADO.NET
PPS
Ado.net session01
PPT
Mongo db basics
A pain free migraine
Session06 handling xml data
CaseStudy-MohammedImranAlam-Xcelsius
Visualizing STEP Files
Disconnected data
Ado.net
Ado.net session05
Prg421
Exercises
Ado.net session02
ADO.NET by ASP.NET Development Company in india
Chapter6 database connectivity
Laboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y Salto
11 qmds2005 session16
Ado.net session04
Hibernate II
ASP.NET 09 - ADO.NET
Ado.net session01
Mongo db basics
Ad

Viewers also liked (17)

PPT
Introto netthreads-090906214344-phpapp01
PPT
Advancedrn
PDF
Going beyond-data-and-analytics-v4
PDF
worklight_development_environment
PPT
Collaborative filtering hyoungtae cho
PPTX
Caqa5e ch4
DOCX
Asp controls
PPT
PPT
Role of locking- cds
PPT
DOCX
Intellij idea features
PPT
(148064384) bfs
PDF
Big data trendsdirections nimführ.ppt
PDF
Hans enocson how big data creates opportunities for productivity improvements...
PDF
Visual studio-2012-product-guide
Introto netthreads-090906214344-phpapp01
Advancedrn
Going beyond-data-and-analytics-v4
worklight_development_environment
Collaborative filtering hyoungtae cho
Caqa5e ch4
Asp controls
Role of locking- cds
Intellij idea features
(148064384) bfs
Big data trendsdirections nimführ.ppt
Hans enocson how big data creates opportunities for productivity improvements...
Visual studio-2012-product-guide
Ad

Similar to Android sql examples (20)

DOCX
Android database tutorial
PPTX
Unit - IV (1).pptx
PPTX
Unit - IV.pptx
PPTX
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
DOCX
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
PPTX
Create an android app for database creation using.pptx
DOCX
Accessing data with android cursors
DOCX
Accessing data with android cursors
PDF
Android-Chapter17-SQL-Data persistency in android databases
PPTX
Contains the SQLite database management classes that an application would use...
PPTX
Lecture 10: Android SQLite database.pptx
PPTX
Database in Android
PPTX
Databases in Android Application
PDF
Android development beyond the basics
PPT
Sqlite
PDF
Android App Development 05 : Saving Data
PPTX
Android Training (Storing data using SQLite)
PDF
Android Level 2
PPTX
Android Database
ODP
Session 2- day 3
Android database tutorial
Unit - IV (1).pptx
Unit - IV.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
Create an android app for database creation using.pptx
Accessing data with android cursors
Accessing data with android cursors
Android-Chapter17-SQL-Data persistency in android databases
Contains the SQLite database management classes that an application would use...
Lecture 10: Android SQLite database.pptx
Database in Android
Databases in Android Application
Android development beyond the basics
Sqlite
Android App Development 05 : Saving Data
Android Training (Storing data using SQLite)
Android Level 2
Android Database
Session 2- day 3

Recently uploaded (20)

PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Sustainable Sites - Green Building Construction
PDF
composite construction of structures.pdf
PPT
Project quality management in manufacturing
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPT
Mechanical Engineering MATERIALS Selection
PPTX
additive manufacturing of ss316l using mig welding
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
web development for engineering and engineering
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
PPT on Performance Review to get promotions
PPTX
Lecture Notes Electrical Wiring System Components
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Sustainable Sites - Green Building Construction
composite construction of structures.pdf
Project quality management in manufacturing
Lesson 3_Tessellation.pptx finite Mathematics
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Mechanical Engineering MATERIALS Selection
additive manufacturing of ss316l using mig welding
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
CH1 Production IntroductoryConcepts.pptx
web development for engineering and engineering
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPT on Performance Review to get promotions
Lecture Notes Electrical Wiring System Components
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx

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; }
  • 94. set{ sqldb_available = value; } } //Gets or sets the value for message handling public string Message { get{ return sqldb_message; } set{ sqldb_message = value; } } //Creates a new database which name is given by the parameter public void CreateDatabase(string sqldb_name) { try { sqldb_message = ""; string sqldb_location = System.Environment.GetFolderPath(System. Environment.SpecialFolder.Personal); string sqldb_path = Path.Combine(sqldb_location, sqldb_name); bool sqldb_exists = File.Exists(sqldb_path); if(!sqldb_exists) { sqldb = SQLiteDatabase.OpenOrCreateDatabase(sqldb_path,null ); sqldb_query = "CREATE TABLE IF NOT EXISTS MyTable (_id I NTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR, LastName VARCHAR, Age INT);"; sqldb.ExecSQL(sqldb_query); sqldb_message = "Database: " + sqldb_name + " created"; }
  • 95. else { sqldb = SQLiteDatabase.OpenDatabase(sqldb_path, null, Databa seOpenFlags.OpenReadwrite); sqldb_message = "Database: " + sqldb_name + " opened"; } sqldb_available=true; } catch(SQLiteException ex) { sqldb_message = ex.Message; } } //Adds a new record with the given parameters public void AddRecord(string sName, string sLastName, int iAge) { try { sqldb_query = "INSERT INTO MyTable (Name, LastName, Age) VA LUES ('" + sName + "','" + sLastName + "'," + iAge + ");"; sqldb.ExecSQL(sqldb_query); sqldb_message = "Record saved"; } catch(SQLiteException ex) { sqldb_message = ex.Message; } }
  • 96. //Updates an existing record with the given parameters depending on id p arameter public void UpdateRecord(int iId, string sName, string sLastName, int iAg e) { try { sqldb_query="UPDATE MyTable SET Name ='" + sName + "', Last Name ='" + sLastName + "', Age ='" + iAge + "' WHERE _id ='" + iId + "';"; sqldb.ExecSQL(sqldb_query); sqldb_message = "Record " + iId + " updated"; } catch(SQLiteException ex) { sqldb_message = ex.Message; } } //Deletes the record associated to id parameter public void DeleteRecord(int iId) { try { sqldb_query = "DELETE FROM MyTable WHERE _id ='" + iId + "';"; sqldb.ExecSQL(sqldb_query); sqldb_message = "Record " + iId + " deleted"; } catch(SQLiteException ex) {
  • 97. sqldb_message = ex.Message; } } //Searches a record and returns an Android.Database.ICursor cursor //Shows all the records from the table public Android.Database.ICursor GetRecordCursor() { Android.Database.ICursor sqldb_cursor = null; try { sqldb_query = "SELECT*FROM MyTable;"; sqldb_cursor = sqldb.RawQuery(sqldb_query, null); if(!(sqldb_cursor != null)) { sqldb_message = "Record not found"; } } catch(SQLiteException ex) { sqldb_message = ex.Message; } return sqldb_cursor; } //Searches a record and returns an Android.Database.ICursor cursor //Shows records according to search criteria public Android.Database.ICursor GetRecordCursor(string sColumn, strin g sValue) {
  • 98. Android.Database.ICursor sqldb_cursor = null; try { sqldb_query = "SELECT*FROM MyTable WHERE " + sColumn + " LIKE '" + sValue + "%';"; sqldb_cursor = sqldb.RawQuery(sqldb_query, null); if(!(sqldb_cursor != null)) { sqldb_message = "Record not found"; } } catch(SQLiteException ex) { sqldb_message = ex.Message; } return sqldb_cursor; } } } Records Layout 2. Expand Resources Folder on Solution Pad a) Right click Layout Folder --> Add --> New File… --> Android Layout (record_view)
  • 99. We need a layout for each item we are going to add to our database table. We do not need to define a layout for every item and this same layout can be re- used as many times as the items we have. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:text="ID" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/Id_row" android:layout_weight="1" android:gravity="center" android:textSize="15dp"
  • 101. android:textColor="#ffffffff" android:gravity="center" /> </LinearLayout> Main Layout 3. Expand Resources folder on Solution Pad --> Expand Layout folder a) Double Click Main layout (Main.axml) Xamarin automatically makes Form Widgets's IDs available by referencing Resorce.Id class. Images
  • 102. add.png delete.png save.png search.png Note: I highly recommended putting images into Drawable folder. -Expand Resources Folder ~Right Click Drawable folder --> Add --> Add Files… <?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"> <LinearLayout android:orientation="horizontal" android:minWidth="25px" android:minHeight="25px" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#ff004150"> <TextView android:text="Name" android:gravity="center"
  • 103. android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" android:textSize="20dp" android:textStyle="bold" android:textColor="#ffffffff" /> <TextView android:text="Last Name" android:gravity="center" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" android:textSize="20dp" android:textColor="#ffffffff" android:textStyle="bold" /> <TextView android:text="Age" android:gravity="center" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" android:textSize="20dp" android:textStyle="bold" android:textColor="#ffffffff" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:minWidth="25px"
  • 108. android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@android:color/white" android:layout_weight="1" android:textSize="20dp" android:gravity="center" android:id="@+id/age" /> </LinearLayout> <ListView android:minWidth="25px" android:minHeight="25px" android:layout_width="fill_parent" android:layout_height="match_parent" android:paddingLeft="10dp" android:id="@+id/listItems" /> </LinearLayout> Main Activity class 4. Double Click Main Activity (MainActivity.cs) We have to get object instances from main layout and provide them with an event. Main events will be Add, Edit, Delete and Search for the image buttons we have defined. We have to populate our ListView object with the data stored in the database or create a new one in case it does not exist. namespace BD_Demo
  • 109. { //Main activity for app launching [Activity (Label = "BD_Demo", MainLauncher = true)] public class MainActivity : Activity { //Database class new object Database sqldb; //Name, LastName and Age EditText objects for data input EditText txtName, txtAge, txtLastName; //Message TextView object for displaying data TextView shMsg; //Add, Edit, Delete and Search ImageButton objects for events handling ImageButton imgAdd, imgEdit, imgDelete, imgSearch; //ListView object for displaying data from database ListView listItems; //Launches the Create event for app protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); //Set our Main layout as default view SetContentView (Resource.Layout.Main); //Initializes new Database class object sqldb = new Database("person_db"); //Gets ImageButton object instances imgAdd = FindViewById<ImageButton> (Resource.Id.imgAdd); imgDelete = FindViewById<ImageButton> (Resource.Id.imgDelete); imgEdit = FindViewById<ImageButton> (Resource.Id.imgEdit); imgSearch = FindViewById<ImageButton> (Resource.Id.imgSearch);
  • 110. //Gets EditText object instances txtAge = FindViewById<EditText> (Resource.Id.txtAge); txtLastName = FindViewById<EditText> (Resource.Id.txtLastName); txtName = FindViewById<EditText> (Resource.Id.txtName); //Gets TextView object instances shMsg = FindViewById<TextView> (Resource.Id.shMsg); //Gets ListView object instance listItems = FindViewById<ListView> (Resource.Id.listItems); //Sets Database class message property to shMsg TextView instance shMsg.Text = sqldb.Message; //Creates ImageButton click event for imgAdd, imgEdit, imgDelete and imgSearch imgAdd.Click += delegate { //Calls function AddRecord for adding a new record sqldb.AddRecord (txtName.Text, txtLastName.Text, int.Parse (txtAg e.Text)); shMsg.Text = sqldb.Message; txtName.Text = txtAge.Text = txtLastName.Text = ""; GetCursorView(); }; imgEdit.Click += delegate { int iId = int.Parse(shMsg.Text); //Calls UpdateRecord function for updating an existing record sqldb.UpdateRecord (iId, txtName.Text, txtLastName.Text, int.Parse (txtAge.Text)); shMsg.Text = sqldb.Message; txtName.Text = txtAge.Text = txtLastName.Text = "";
  • 111. GetCursorView(); }; imgDelete.Click += delegate { int iId = int.Parse(shMsg.Text); //Calls DeleteRecord function for deleting the record associated to id parameter sqldb.DeleteRecord (iId); shMsg.Text = sqldb.Message; txtName.Text = txtAge.Text = txtLastName.Text = ""; GetCursorView(); }; imgSearch.Click += delegate { //Calls GetCursorView function for searching all records or single re cord according to search criteria string sqldb_column = ""; if (txtName.Text.Trim () != "") { sqldb_column = "Name"; GetCursorView (sqldb_column, txtName.Text.Trim ()); } else if (txtLastName.Text.Trim () != "") { sqldb_column = "LastName"; GetCursorView (sqldb_column, txtLastName.Text.Trim ()); } else if (txtAge.Text.Trim () != "")
  • 112. { sqldb_column = "Age"; GetCursorView (sqldb_column, txtAge.Text.Trim ()); } else { GetCursorView (); sqldb_column = "All"; } shMsg.Text = "Search " + sqldb_column + "."; }; //Add ItemClick event handler to ListView instance listItems.ItemClick += new EventHandler<AdapterView.ItemClickEvent Args> (item_Clicked); } //Launched when a ListView item is clicked void item_Clicked (object sender, AdapterView.ItemClickEventArgs e) { //Gets TextView object instance from record_view layout TextView shId = e.View.FindViewById<TextView> (Resource.Id.Id_ro w); TextView shName = e.View.FindViewById<TextView> (Resource.Id.N ame_row); TextView shLastName = e.View.FindViewById<TextView> (Resource.I d.LastName_row); TextView shAge = e.View.FindViewById<TextView> (Resource.Id.Age _row); //Reads values and sets to EditText object instances txtName.Text = shName.Text;
  • 113. txtLastName.Text = shLastName.Text; txtAge.Text = shAge.Text; //Displays messages for CRUD operations shMsg.Text = shId.Text; } //Gets the cursor view to show all records void GetCursorView() { Android.Database.ICursor sqldb_cursor = sqldb.GetRecordCursor (); if (sqldb_cursor != null) { sqldb_cursor.MoveToFirst (); string[] from = new string[] {"_id","Name","LastName","Age" }; int[] to = new int[] { Resource.Id.Id_row, Resource.Id.Name_row, Resource.Id.LastName_row, Resource.Id.Age_row }; //Creates a SimplecursorAdapter for ListView object SimpleCursorAdapter sqldb_adapter = new SimpleCursorAdapter (t his, Resource.Layout.record_view, sqldb_cursor, from, to); listItems.Adapter = sqldb_adapter; } else { shMsg.Text = sqldb.Message; }
  • 114. } //Gets the cursor view to show records according to search criteria void GetCursorView (string sqldb_column, string sqldb_value) { Android.Database.ICursor sqldb_cursor = sqldb.GetRecordCursor (sql db_column, sqldb_value); if (sqldb_cursor != null) { sqldb_cursor.MoveToFirst (); string[] from = new string[] {"_id","Name","LastName","Age" }; int[] to = new int[] { Resource.Id.Id_row, Resource.Id.Name_row, Resource.Id.LastName_row, Resource.Id.Age_row }; SimpleCursorAdapter sqldb_adapter = new SimpleCursorAdapter (t his, Resource.Layout.record_view, sqldb_cursor, from, to); listItems.Adapter = sqldb_adapter; } else { shMsg.Text = sqldb.Message; } } }
  • 115. } 5. Build solution and run Ok, so that's it for today! I hope that this tutorial has been useful. Feel free to make any questions, complaints, suggestions or comments. Happy coding! How to Check Database Using SQLite Manager in Android By Sazid Mauhammad on Feb 26, 2013 In this article I tell you how to see your SQLite database, if you want to see the details, using SQLite Manager.  21.8k  1  1
  • 116.  facebook  twitter  linkedIn  google Plus  o o o o o o o o o o o o o  expand Download Aspose, it really helps Introduction In this article I tell you how to see your SQLite database, if you want to see the details. You can see your SQLite database in three ways. 1. Using a command prompt in window. 2. Using coding, to see details you can get using code in your project. 3. Using SQLite manager. Here I explain how to use SQLIte manager. To see details of your database you must use the following procedure. Step 1 First, open any web browser and add to it the SQLite Manager add-on as shown in the following image.
  • 117. Step 2 Now create a project to save your database using SQLite database as I did in my last article Create Database in Android. Step 3 Open DDMS Perspective in your Eclipse editor and go to the File Explorer and select "Data" -> "Data" then enter your project package name ( in my case its "com.db.documents" ) as shown in the following image:
  • 118. Step 4 Now pull outside selective database from your device using the pull button and save the database with a ".db"extension as shown in the following image:
  • 119. Save it as "database.db":
  • 120. Step 5 Now open your browser and open SQLite Manager using "Tool" -> "SQLIte Manager" as shown in the following image:
  • 121. Steps 6 Connect to your database as shown in the following image:
  • 122. Step 7 And at last you will see the new database in your project as shown below: