Android Studio y SQLite Database Tutorial
Android Studio y SQLite Database Tutorial
Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials
publication in eBook ($9.99) or Print ($38.99) format
Android Studio Development Essentials - Android 6 Edition Print and eBook (ePub/PDF/Kindle)
editions contain 65 chapters.
eBookFrenzy.com
The chapter entitled An Overview of Android SQLite Databases in Android Studio covered the basic principles of
integrating relational database storage into Android applications using the SQLite database management system.
The previous chapter took a minor detour into the territory of designing TableLayouts within the Android Studio
Designer tool, in the course of which, the user interface for an example database application was created. In this
chapter, work on the Database application project will be continued with the ultimate objective of completing the
database example.
Contents
[hide]
Table 42-1
package com.ebookfrenzy.database;
public Product() {
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;
@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;
@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:
SQLiteDatabase db = this.getWritableDatabase();
Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials
publication in eBook ($9.99) or Print ($38.99) format
Android Studio Development Essentials - Android 6 Edition Print and eBook (ePub/PDF/Kindle)
editions contain 65 chapters.
eBookFrenzy.com
SQLiteDatabase db = this.getWritableDatabase();
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;
}
String query = "Select * FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME
+ " = \"" + productname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
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;
}
<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;
TextView idView;
EditText productBox;
EditText quantityBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
int quantity =
Integer.parseInt(quantityBox.getText().toString());
Product product =
new Product(productBox.getText().toString(), quantity);
dbHandler.addProduct(product);
productBox.setText("");
quantityBox.setText("");
}
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");
}
}
if (result)
{
idView.setText("Record Deleted");
productBox.setText("");
quantityBox.setText("");
}
else
idView.setText("No Match Found");
}
.
.
.
}
Summary
The purpose of this chapter has been to work step by step through a practical application of SQLite based database
storage in Android applications. As an exercise to develop your new database skill set further, consider extending
the example to include the ability to update existing records in the database table.