SQLite is a Structure query base database, open source, light weight, no network access and standalone database. It support embedded relational database features.
Whenever an application needs to store large amount of data then using sqlite is more preferable than other repository system like SharedPreferences or saving data in files.
Android has built in SQLite database implementation. It is available locally over the device(mobile & tablet) and contain data in text format. It carry light weight data and suitable with many languages. So, it doesn’t required any administration or setup procedure of the database.
Important Note – The database created is saved in a directory: data/data/APP_Name/databases/DATABASE_NAME.
Table of Contents
For creating, updating and other operations you need to create a subclass or SQLiteOpenHelper class. SQLiteOpenHelper is a helper class to manage database creation and version management. It provides two methods onCreate(SQLiteDatabase db), onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion).
The SQLiteOpenHelper is responsible for opening database if exist, creating database if it does not exists and upgrading if required. The SQLiteOpenHelper only require the DATABASE_NAME to create database. After extending SQLiteOpenHelper you will need to implement its methods onCreate, onUpgrade and constructor.
onCreate(SQLiteDatabase sqLiteDatabase) method is called only once throughout the application lifecycle. It will be called whenever there is a first call to getReadableDatabase() or getWritableDatabase() function available in super SQLiteOpenHelper class. So SQLiteOpenHelper class call the onCreate() method after creating database and instantiate SQLiteDatabase object. Database name is passed in constructor call.
onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) is only called whenever there is a updation in existing version. So to update a version we have to increment the value of version variable passed in the superclass constructor.
In onUpgrade method we can write queries to perform whatever action is required. In most example you will see that existing table(s) are being dropped and again onCreate() method is being called to create tables again. But it’s not mandatory to do so and it all depends upon your requirements.
We have to change database version if we have added a new row in the database table. If we have requirement that we don’t want to lose existing data in the table then we can write alter table query in the onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) method.
Get Better Understanding of Sqlite Before You Read Example – To get better understanding of SQlite database, it is recommended you read below article first:
In this example we simply want to illustrate the insert, update, delete and more operations of SQLite over a table in Android Studi. We created a activity having textview, button and edittext over it. Another class which extends SQLiteOpenHelper where the create and insert operations will be carried out. The example contain proper validation like you need to enter data before executing any operation.
Below you can download code, see final output and step by step explanation:
Step 1: Create a New Project and Name it SQLiteOperations.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we create a layout in our XML file adding textbox, buttons, edittext. On button onclick is defined which associate it with related function.
Step 3 : Now open app -> java -> package -> MainActivity.java and add the below code.
In this step we used the functions that linked via the button click. These functions are defined in other class and are used here. Each function return value that define no of rows updated, using that we defined whether operation is successful or not. Also user need to define valid data to perform operation empty fields will not be entertained and return error .
package com.example.sqliteoperations; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity < EditText Name, Pass , updateold, updatenew, delete; myDbAdapter helper; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Name= (EditText) findViewById(R.id.editName); Pass= (EditText) findViewById(R.id.editPass); updateold= (EditText) findViewById(R.id.editText3); updatenew= (EditText) findViewById(R.id.editText5); delete = (EditText) findViewById(R.id.editText6); helper = new myDbAdapter(this); >public void addUser(View view) < String t1 = Name.getText().toString(); String t2 = Pass.getText().toString(); if(t1.isEmpty() || t2.isEmpty()) < Message.message(getApplicationContext(),"Enter Both Name and Password"); >else < long if(id<=0) < Message.message(getApplicationContext(),"Insertion Unsuccessful"); Name.setText(""); Pass.setText(""); >else < Message.message(getApplicationContext(),"Insertion Successful"); Name.setText(""); Pass.setText(""); >> > public void viewdata(View view) < String data = helper.getData(); Message.message(this,data); >public void update( View view) < String u1 = updateold.getText().toString(); String u2 = updatenew.getText().toString(); if(u1.isEmpty() || u2.isEmpty()) < Message.message(getApplicationContext(),"Enter Data"); >else < int a= helper.updateName( u1, u2); if(a<=0) < Message.message(getApplicationContext(),"Unsuccessful"); updateold.setText(""); updatenew.setText(""); >else < Message.message(getApplicationContext(),"Updated"); updateold.setText(""); updatenew.setText(""); >> > public void delete( View view) < String uname = delete.getText().toString(); if(uname.isEmpty()) < Message.message(getApplicationContext(),"Enter Data"); >else < int a= helper.delete(uname); if(a<=0) < Message.message(getApplicationContext(),"Unsuccessful"); delete.setText(""); >else < Message.message(this, "DELETED"); delete.setText(""); >> > >
Step 4: In this step create a java class myDbAdapter. java.
In this we define the functions that are used to perform the operations insert, update and delete operations in SQLite. Further this class create another class that will extend the SQLiteOpenHelper. Each function carry equivalent methods that perform operations.
Important Note – According to naming convention it is suggested to define primary key starting with underscore example: _id.
package com.example.sqliteoperations; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class myDbAdapter < myDbHelper myhelper; public myDbAdapter(Context context) < myhelper = new myDbHelper(context); >public long insertData(String name, String pass) < SQLiteDatabase dbb = myhelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(myDbHelper.NAME, name); contentValues.put(myDbHelper.MyPASSWORD, pass); long null , contentValues); return id; >public String getData() < SQLiteDatabase db = myhelper.getWritableDatabase(); String[] columns = ; Cursor cursor =db.query(myDbHelper.TABLE_NAME,columns,null,null,null,null,null); StringBuffer buffer= new StringBuffer(); while (cursor.moveToNext()) < int cid =cursor.getInt(cursor.getColumnIndex(myDbHelper.UID)); String name =cursor.getString(cursor.getColumnIndex(myDbHelper.NAME)); String password =cursor.getString(cursor.getColumnIndex(myDbHelper.MyPASSWORD)); buffer.append(cid+ " " + name + " " + password +" \n"); >return buffer.toString(); > public int delete(String uname) < SQLiteDatabase db = myhelper.getWritableDatabase(); String[] whereArgs =; int count =db.delete(myDbHelper.TABLE_NAME ,myDbHelper.NAME+" = ?",whereArgs); return count; > public int updateName(String oldName , String newName) < SQLiteDatabase db = myhelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(myDbHelper.NAME,newName); String[] whereArgs= ; int count =db.update(myDbHelper.TABLE_NAME,contentValues, myDbHelper.NAME+" = ?",whereArgs ); return count; > static class myDbHelper extends SQLiteOpenHelper < private static final String DATABASE_NAME = "myDatabase"; // Database Name private static final String TABLE_NAME = "myTable"; // Table Name private static final int DATABASE_Version = 1;. // Database Version private static final String UID="_id"; // Column I (Primary Key) private static final String NAME = "Name"; //Column II private static final String MyPASSWORD= "Password"; // Column III private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+ " ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255) ,"+ MyPASSWORD+" VARCHAR(225));"; private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME; private Context context; public myDbHelper(Context context) < super(context, DATABASE_NAME, null, DATABASE_Version); this.context=context; >public void onCreate(SQLiteDatabase db) < try < db.execSQL(CREATE_TABLE); >catch (Exception e) < Message.message(context,""+e); >> @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) < try < Message.message(context,"OnUpgrade"); db.execSQL(DROP_TABLE); onCreate(db); >catch (Exception e) < Message.message(context,""+e); >> > >
Step 5: In this step create another java class Message.class
In this just simply add toast for displaying message. This is optional, it is just added to again and again defining toast in the example.
package com.example.sqliteoperations; import android.content.Context; import android.widget.Toast; public class Message < public static void message(Context context, String message) < Toast.makeText(context, message, Toast.LENGTH_LONG).show(); >>
Output
Now run the app and view the functionality added over the buttons.
To understand how to add or retrieve image from phone external storage to application using SQLite Database. Please read our step by step add & retrieve image from SQLite tutorial.