Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Android sql examples
1. Android Developer
m a r t e s , 7 d e e n e r o d e 2 0 1 4
Connect DB SQLite to Android With Android Studio
Connect DB SQLite to Android With Android Studio
CREATE FAST APPS HERE
DOWNLOAD ALL THE PROYECT HERE
One of the first and more important information are: How to connect SQLite with Android app?
For this tutorial I am using Android Studio. You can download this from HERE
First we need to create we database. I am using SQLite Manager (this is a plugin for Firefox).
I create a Data Base named "example" and a table named "exampleTable".
CREATE TABLE exampleTable ( name VARCHAR(200) NULL DEFAULT NULL, lastname
VARCHAR(200) NULL DEFAULT NULL, ID VARCHAR(20) NULL DEFAULT NULL )
INSERT INTO exampleTable VALUES('Jhon', 'Sweet', '1');
INSERT INTO exampleTable VALUES('Audrey', 'Owen', '2');
INSERT INTO exampleTable VALUES('Michelle', 'Peters', '3');
INSERT INTO exampleTable VALUES('Helen', 'Black', '4');
INSERT INTO exampleTable VALUES('Jessica', 'Sweet', '5');
When the database are create, we need to put in the assent folder, in the Android Studio Proyect.
2. Then we create a Connection class.
In this class are two important lines in this class:
private static String DB_PATH = "/data/data/com.example.databaseconnect/databases/";
private static String DB_NAME = "example.sqlite";
HOW TO CREATE APPS. GO HERE
The DB_PATH is the folder where the Data Bare are. The path of this are "/data/data/Pakage
Name/databases/"
And DB_NAME is the Data Base name.
You can see the Data Base in the "Android Debug Monitor". To open the Android Debug Monitor you
3. need go to the Android icon ( ).
Then show this:
We need to use the DDMS. This right up.
Then we select in the left the "Package name", in my case it would
be"com.example.databaseconnect"
And then in the right go to: data -> data -> package name -> database, in this folder are the Data Base.
Return to the code, you need to create, copy, check, open and then connect the Data Base to the
Device, for this in the Connect.java class create the nexts functions.
4. Then create another class named "DataDB.java" to connect with "Connect.java" class
5. And to finish in the MainActivity.java, only call the getNameDB and DONE.
Screenshots
(This page is really obsolete. We need to update these screenshots to showAndroid Studio.)
This page contains some screenshots showing the ADT in action.
Visual Layout Editor
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"
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;
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);
}
}
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);
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);
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"
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; }