Creating a SQLite Database in Android Apps

Deal Score0

Creating a SQLite Database in Android Apps . It is advisable to read the article Getting to know SQLite Database On Android app before continuing this tutorial.

Steps Make a SQLite Database

1. Define the scheme (Define Schema).
Define the database name, version, table names, and column names.
2. Creating a database (Create Database).
Write queries to create / modify database.
3. Query Execution (Execute Queries)
execution of queries such as insert, update, delete and more.

1.Definisikan scheme (Define Schema).

dvbtr

 

Sample database

The above image is an example of a database that will be used in this tutorial. To learn schema defines the following code.

Database_name String = "teknorialdatabase.db" ; // can also write extensions without .db
TABLE_NAME String = "teknorialtable" ;
String UID = "_ id" ;
String NAME = "Name" ;
DATABASE_VERSION int = 1 ;

2. Create a database (Create Database) using SQLiteOpenHelper.

Create a subclass of SQLiteOpenHelper implement onCreate (SQLiteOpenHelper), and onUpgrade (SQLiteDatabase, int, int). This class will open the database if any, create a database if it does not exist and clicking upgade if needed.

RezaHelper class  extends  SQLiteOpenHelper
{
	private  static  final String database_name = "teknorialdatabase.db" ;
	private  static  final String TABLE_NAME = "teknorialtable" ;
	private  static  final String UID = "_ id" ;
	private  static  final String NAME = "Name" ;
	private  static  final  int DATABASE_VERSION = 1 ;
	RezaHelper (Context context)
	{
		super (context, Database_name, null , DATABASE_VERSION);
	}
	public  void  onCreate  (SQLiteDatabase db)
	{
	}
	public  void  onUpgrade  (SQLiteDatabase db, OldVersion int , int newVersion)
	{
	}	
}

– OnCreate (): Called when the database can be accessed However the yet to be made. Table creation and initial data in the table should be placed here.
– OnUpdate (): Called when the database needs upgraded. Use this method to drop tables, plus tables, or other things that need to be upgraded version of the new scheme.
If you want to add a column to use ALTER TABLE to add a new colom to the table and if you want to rename or remove columns can also use the ALTER TABLE.

3. Execute Query (Execute Queries) with SQLiteDatabase

SQLiteDatabase has a method to create, delete, execute SQL commands and perform management tasks more common database. The database name must be unique within an application, not the same in all applications. To execute SQL commands use the public methods of the class SQLiteDatabase following:

public  void  execSQL  (String sql)


This method can only execute a single SQL statement but not for SQL SELECT statement or other mereturn data. Multiple Statment by separating by a semicolon (semicolon) is not supported by this method. If the SQL string is not valid for use throws SQLException error handling.

implementation onCreate

RezaHelper class  extends  SQLiteOpenHelper
{
	private  static  final String database_name = "teknorialdatabase.db" ;
	private  static  final String TABLE_NAME = "teknorialtable" ;
	private  static  final String UID = "_ id" ;
	private  static  final String NAME = "Name" ;
	private  static  final int DATABASE_VERSION = 1 ;
	RezaHelper (Context context)
	{
		super (context, Database_name, null , DATABASE_VERSION);
	}
	public void onCreate (SQLiteDatabase db)
	{
		db.execSQL ( "CREATE TABLE teknorialtable (_id INTEGER PRIMARY KEY
			AUTOINCREMENT, Name VARCHAR (255)); " );
	} Catch (SQLException e) {
		e.printStackTrace ();
	}
	public void onUpgrade (SQLiteDatabase db, OldVersion int, int newVersion)
	{
		
	}
}


implementation onUpdate

RezaHelper class  extends  SQLiteOpenHelper
{
	private  static  final String database_name = "teknorialdatabase.db" ;
	private  static  final String TABLE_NAME = "teknorialtable" ;
	private  static  final String UID = "_ id" ;
	private  static  final String NAME = "Name" ;
	private  static  final  int DATABASE_VERSION = 1 ;
	RezaHelper (Context context)
	{
		super (context, Database_name, null , DATABASE_VERSION);
	}
	public  void  onCreate  (SQLiteDatabase db)
	{
	  ...
	}
	public  void  onUpgrade  (SQLiteDatabase db, OldVersion int , int newVersion)
	{
	   db.execSQL ( "DROP TABLE IF EXISTS teknorialtable" );
		onCreate (db);	
	}
}

Tutorial create SQLite database applications with Android Studio

1. Create a new class with the name message.java and follow the following code.This class is useful for getting a message that can be used to see the error in SQL statment or can also see the process create and upgrade the database.

com.teknorial.belajardatabase package ;

/ **
 * Created by Teknorial on 22 -Nov- 15.
 * /
android.content.Context import ;
android.widget.Toast import ;

public  class  Message  {
    public  static  void  message  (Context context, String message)
    {
        Toast.makeText (context, message, Toast.LENGTH_LONG) .show ();
    }
}

2. Create a new class which is a subclass of class SQLiteOpenHelper with RezaHelper.java name.

com.teknorial.belajardatabase package ;

android.content.Context import ;
android.database.sqlite.SQLiteDatabase import ;
android.database.sqlite.SQLiteException import ;
android.database.sqlite.SQLiteOpenHelper import ;


/ **
 * Created by Teknorial on 22 -Nov- 15.
 * /
public  class  extends  RezaHelper  SQLiteOpenHelper  {

    private  static  final String database_name = "teknorialdatabase" ;
    private  static  final String TABLE_NAME = "teknorialtable" ;
    private  static  final String UID = "_ id" ;
    private  static  final String NAME = "Name" ;
    private  static  final  int DATABASE_VERSION = 1 ;
    private  static  final String create_table = "CREATE TABLE" + TABLE_NAME + "(" + UID + "INTEGER PRIMARY KEY AUTOINCREMENT," + NAME + "VARCHAR (255));" ;
    private  static  final String DROP_TABLE = "DROP TABLE IF EXISTS" + TABLE_NAME;
    private Context context;
    public  RezaHelper  (Context context)  {
        super (context, Database_name, null , DATABASE_VERSION);
        this .context = context;
        Message.message (context, "Constructor called" );
    }

    @Override
    public  void  onCreate  (SQLiteDatabase db)  {
        try {
            db.execSQL (create_table);
            Message.message (context, "onCreate called" );
        } Catch (SQLiteException e) {
            Message.message (context, "" + e);
        }
    }


    @Override
    public  void  onUpgrade  (SQLiteDatabase db, OldVersion int , int newVersion)  {
        try {
            Message.message (context, "onUpgrade called" );
            db.execSQL (DROP_TABLE);
            onCreate (db);
        } Catch (SQLiteException e) {
            Message.message (context, "" + e);
        }
    }
}

3. Modify the class MainActivity as follows.

com.teknorial.belajardatabase package ;


android.app.Activity import ;
android.database.sqlite.SQLiteDatabase import ;
android.os.Bundle import ;


public  class  MainActivity  extends  Activity  {
    RezaHelper rezaHelper;
    @Override
    protected  void  onCreate  (Bundle savedInstanceState)  {
        super .onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        rezaHelper = new RezaHelper ( this );
        SQLiteDatabase sqLiteDatabase = rezaHelper.getWritableDatabase ();
    }

}

If the application is successful we will look like the screenshot below.

constructor-dipanggil

 

constructor called

At the time of the first application installed will appear called onCreate message means the database yet exist and will be created.

onCreate-dipanggil

 

onCreate called

To try to view the database upgrade, change into DATABASE_VERSION DATABASE_VERSION = 1 = 2, and will be called and the onUpgrade message pops followed by a message onCreate called. For a discussion of other SQLite queries such as SELECT, INSERT, and others will follow.

Thus the article Creating a SQLite Database in Android Apps. Keep up teknorial.com to know a lot about programming android. Do not forget to Like Teknorial FansPage on Facebook and Google Plus to get the latest updates from teknorial.com. If you have any questions please do not hesitate to ask dikotak comment. Thank you

Source Code : SQLiteDatabaseApp

Referensi: SQLiteDatabase

http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

Storage Options – SQLite Databases

http://developer.android.com/guide/topics/data/data-storage.html#db

Saving Data in SQL Databases

http://developer.android.com/training/basics/data-storage/ databases.html

Please follow and like us:
0

We will be happy to hear your thoughts

Leave a reply