unknown os platform
Android SQLite database step by step tutorial for beginners | Whats-online.info

Android SQLite database step by step tutorial for beginners

2017/02/02 / Science and Tutorials

Android tutorial for beginners.Learn how to create step by step an android SQLite database in Android studio. Besides, insert, update,delete, read data from DB.See example

sqlite database in android example step by step

Download source code example at the end of this post

First and foremost, we can define an Android SQLite as an open source SQL database that stores data to a text file on a device. 
In short, is a platform that manages data in an application. It has methods to create, read, update, delete, execute SQL commands, and perform other common database management tasks.
As a developer, we need to ask yourself, which is the best way to store data in our application? Android platform provides several ways in which you can store data locally in our Android app and access it for later use. For this post, I will only discuss on how to store data using SQLite database.
Note, this android tutorial covers step by step procedures for creating a DB to performing all CRUD operations.

So here is the complete step by step tutorial for Android SQLite  database (Insert Update Delete and Display data) example tutorial with source code 

This post covers:-
1.How to create an SQLite database
2.How to build tables
3.How to insert data to the tables
4.How to read data from the tables
5.How to update and delete data from the tables
6.How to display the data from the tables using listview

list of our activity classes

list of our XML files

Let us code.
First, we need to lay out our interface. I will demonstrate this post using the following widgets

Edittext widget - Enter our data
button - save and display data
listview widget - list the data from the database as shown by the image below


This XML code lays out our interface.

Entire activity_main.xml Code

<LinearLayout 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:orientation="vertical"     tools:context=".MainActivity">     <TextView android:text="Register "         android:layout_gravity="center"         android:layout_width="wrap_content"         android:layout_height="wrap_content" />     <EditText         android:layout_width="match_parent"         android:layout_height="50dp"         android:id="@+id/txt1"         android:hint="Enter your first name"         android:layout_margin="10dp"/>     <EditText         android:layout_width="match_parent"         android:layout_height="50dp"         android:id="@+id/txt2"         android:hint="Enter your first name"         android:layout_margin="10dp"/>     <EditText         android:layout_width="match_parent"         android:layout_height="50dp"         android:id="@+id/txt3"         android:hint="Enter your Phone number"         android:layout_margin="10dp"/>     <LinearLayout         android:layout_width="match_parent"         android:orientation="horizontal"         android:gravity="center"         android:layout_height="wrap_content">         <Button             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:onClick="buttonClicked"             android:id="@+id/save"             android:text="Save"/>         <Button             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:onClick="buttonClicked"             android:id="@+id/display"             android:text="Display"/>     </LinearLayout>     <LinearLayout         android:layout_width="match_parent"         android:layout_height="match_parent">         <ListView             android:layout_width="match_parent"             android:layout_height="match_parent"             android:id="@+id/list1"/>     </LinearLayout> </LinearLayout>


Gets data from the edittext, passes it to the DatabaseHandler.java via Contact.java and also displays it on our listview from the DB.

 package info.whats_online.sqlitedb; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends Activity {     private EditText fname,sname,phone;     private DatabaseHandler db;     private String f_name,s_name,p_no;     private  ListView lv;     private dataAdapter data;     private Contact dataModel;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         //Instantiate database handler         db=new DatabaseHandler(this);         lv = (ListView) findViewById(R.id.list1);         fname=(EditText) findViewById(R.id.txt1);         sname=(EditText) findViewById(R.id.txt2);         phone=(EditText) findViewById(R.id.txt3);     }     public void buttonClicked(View v){        int id=v.getId();         switch(id){             case R.id.save:                     addContact();                 break;             case R.id.display:                         ShowRecords();                 break;         }     }     // function to get values from the Edittext     private void getValues(){         f_name = fname.getText().toString();         s_name = sname.getText().toString();         p_no = phone.getText().toString();     }            //Insert data to the database     private void addContact(){         getValues();         db.addContacts(new Contact(f_name, s_name, p_no));         Toast.makeText(getApplicationContext(),"Saved successfully", Toast.LENGTH_LONG).show();     }           //Retrieve data from the database and set to the list view     private void ShowRecords(){         final ArrayList<Contact> contacts = new ArrayList<>(db.getAllContacts());         data=new dataAdapter(this, contacts);                  lv.setAdapter(data);         lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {             @Override             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {                 dataModel = contacts.get(position);                Toast.makeText(getApplicationContext(),String.valueOf(dataModel.getID()), Toast.LENGTH_SHORT).show();             }         });     } }


getValues() function gets the values from the Edittext
addContact() function passes the values to the database
ShowRecords() function displays the values to the listview.


Performs all CRUD operations, that is, Insert, Read, Update, Delete.
Also, we will define our database and our table in this class.

package info.whats_online.sqlitedb; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; /**  * Created by sada on 1/31/2017.  */ public class DatabaseHandler extends SQLiteOpenHelper {     // Database Version     private static final int DATABASE_VERSION = 1;     // Database Name     private static final String DATABASE_NAME = "contactsManager";     // Contacts table name     private static final String TABLE_CONTACTS = "contacts";     // Contacts Table Columns names     private static final String KEY_ID = "id";     private static final String KEY_FNAME = "fname";     private static final String KEY_SNAME = "sname";     private static final String KEY_PH_NO = "phone_number";     public DatabaseHandler(Context context) {         super(context, DATABASE_NAME, null, DATABASE_VERSION);     }     //Create tables     @Override     public void onCreate(SQLiteDatabase db) {        String CREATE_TABLE_CONTACTS="CREATE TABLE " + TABLE_CONTACTS + "("                + KEY_ID +" INTEGER PRIMARY KEY,"                + KEY_FNAME +" TEXT,"                + KEY_SNAME +" TEXT,"                + KEY_PH_NO  +" TEXT" + ")";         db.execSQL(CREATE_TABLE_CONTACTS);     }     // Upgrading database     @Override     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {         // Drop older table if existed         db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);         // Create tables again         onCreate(db);     }     /**      * All CRUD(Create, Read, Update, Delete) Operations      */     //Insert values to the table contacts     public void addContacts(Contact contact){       SQLiteDatabase db = this.getReadableDatabase();         ContentValues values=new ContentValues();         values.put(KEY_FNAME, contact.getFName());         values.put(KEY_SNAME, contact.getSName() );         values.put(KEY_PH_NO, contact.getPhoneNumber());         db.insert(TABLE_CONTACTS, null, values);         db.close();     }     /**      *Getting All Contacts      **/     public List<Contact> getAllContacts() {         List<Contact> contactList = new ArrayList<Contact>();         // Select All Query         String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;         SQLiteDatabase db = this.getWritableDatabase();         Cursor cursor = db.rawQuery(selectQuery, null);         // looping through all rows and adding to list         if (cursor.moveToFirst()) {             do {                 Contact contact = new Contact();                 contact.setID(Integer.parseInt(cursor.getString(0)));                 contact.setFName(cursor.getString(1));                 contact.setSName(cursor.getString(2));                 contact.setPhoneNumber(cursor.getString(3));                 // Adding contact to list                 contactList.add(contact);             } while (cursor.moveToNext());         }         // return contact list         return contactList;     }     /**      *Updating single contact      **/     public int updateContact(Contact contact, int id) {         SQLiteDatabase db = this.getWritableDatabase();         ContentValues values = new ContentValues();         values.put(KEY_FNAME, contact.getFName());         values.put(KEY_SNAME, contact.getSName());         values.put(KEY_PH_NO, contact.getPhoneNumber());         // updating row         return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",                 new String[] { String.valueOf(id) });     }     /**      *Deleting single contact      **/     public void deleteContact(int Id) {         SQLiteDatabase db = this.getWritableDatabase();         db.delete(TABLE_CONTACTS, KEY_ID + " = ?",                 new String[] { String.valueOf(Id) });         db.close();     } }


Contains the set and get methods to set the values of our attributes and retrieve the values of our attributes

package info.whats_online.sqlitedb; public class Contact {     //private variables     int _id;     String _fname;     String _sname;     String _phone_number;     // Empty constructor     public Contact(){     }     // constructor     public Contact(int id, String fname, String sname, String phone_number){         this._id = id;         this._fname = fname;         this._sname = sname;         this._phone_number = phone_number;     }     // constructor     public Contact(String fname, String sname, String phone_number){         this._fname = fname;         this._sname = sname;         this._phone_number = phone_number;     }     // getting ID     public int getID(){         return this._id;     }     // setting id     public void setID(int id){         this._id = id;     }     // getting first name     public String getFName(){         return this._fname;     }     // setting first name     public void setFName(String fname){         this._fname = fname;     }     // getting second name     public String getSName(){         return this._sname;     }     // setting first name     public void setSName(String sname){         this._sname = sname;     }     // getting phone number     public String getPhoneNumber(){         return this._phone_number;     }     // setting phone number     public void setPhoneNumber(String phone_number){         this._phone_number = phone_number;     } }


Contains the list adapter to display our data using listview

package info.whats_online.sqlitedb;         import android.content.Context;         import android.view.LayoutInflater;         import android.view.View;         import android.view.ViewGroup;         import android.widget.ArrayAdapter;         import android.widget.TextView;         import java.util.ArrayList; public class dataAdapter extends ArrayAdapter<Contact>{     Context context;     ArrayList<Contact> mcontact;     public dataAdapter(Context context, ArrayList<Contact> contact){         super(context, R.layout.listcontacts, contact);         this.context=context;         this.mcontact=contact;     }     public  class  Holder{         TextView nameFV;         TextView nameSV;         TextView phoneV;     }     @Override     public View getView(int position, View convertView, ViewGroup parent) {         // Get the data item for this position         Contact data = getItem(position);         // Check if an existing view is being reused, otherwise inflate the view         Holder viewHolder; // view lookup cache stored in tag         if (convertView == null) {             viewHolder = new Holder();             LayoutInflater inflater = LayoutInflater.from(getContext());             convertView = inflater.inflate(R.layout.listcontacts, parent, false);             viewHolder.nameFV = (TextView) convertView.findViewById(R.id.txtView1);             viewHolder.nameSV = (TextView) convertView.findViewById(R.id.txtView2);             viewHolder.phoneV = (TextView) convertView.findViewById(R.id.txtView3);             convertView.setTag(viewHolder);         } else {             viewHolder = (Holder) convertView.getTag();         }         viewHolder.nameFV.setText("First Name: "+data.getFName());         viewHolder.nameSV.setText("Second Name: "+data.getSName());         viewHolder.phoneV.setText("Phone no: "+data.getPhoneNumber());         // Return the completed view to render on screen         return convertView;     } }


Lays out elements of our listview 

<?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:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="5dp"         android:id="@+id/txtView1"         />     <TextView         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="5dp"         android:id="@+id/txtView2"        />     <TextView         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="5dp"         android:id="@+id/txtView3"       /> </LinearLayout>

Thanks for your time. Subscribe to our newsletter below to get instant updates direct to your mailbox.

You may also like:

Leave a comment

Subscribe to get replies direct to your mailbox

Submit comment