unknown os platform
how to store data in SQLite database in android example | Whats-online.info

how to store data in SQLite database in android example

2017/02/16 / Science and Tutorials

Android Tutorial: Learn how to create and store data in a simple SQLite database in Android programmatically. See an example

Step by step how to store data in SQLite database in android example

Most Android apps need to save data, even if it is, saving simple data such as storing a key on app launch. Android platform provides different methods of storing data locally onto your application.
For example

    1. Saving key-value pairs of simple data types in a shared preferences file (saving user settings)
    2. Saving arbitrary files in Android's file system (for example images)
    3. Using databases managed by SQLite

 For this Android tutorial, I would like to take through each step of creating, adding tables and inserting data into the SQLite database programmatically.

Note, this tutorial is built on Android Studio.

Download the source code example at the end of this tutorial.

First and foremost, let us create our project. If you're a newbie to programming, follow the link below how to get started with the Android studio.

Our project will have the following classes and XML files.

Java Classes


XML File



Contains the forms where we will input our data. We will demonstrate this tutorial with contact form containing the following edittext
- first name
-second name 
- phone number

Besides, it also contains a 'send button' to send data to the database.

MainActivity.java entire code

package info.whats_online.sqlitedb; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity {     private EditText fname,sname,phone;     private DatabaseHandler db;     private String f_name,s_name,p_no;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         //Instantiate database handler         db=new DatabaseHandler(this);         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;                      }     }     // 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();     }     //Function 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();     } }


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

Contact.java entire code

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;     } }


In this class, we have our database called 'storeContacts',  table 'contacts' and functions to insert data into our database.
Our table will have four columns
column one - (data type integer) is our primary key and contains our contactID index
column two (data type string) - includes our first name index
column three (data type string) - includes our second name index
column four (data type string) - includes our phone number index

DatabaseHandler.java entire code

package info.whats_online.sqlitedb; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /**  * 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 = "storeContacts";     // 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);     }          //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();     } }


Layout our contact forms as shown below.

<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"/>     </LinearLayout> </LinearLayout>

Thanks for visiting our time. Leave a comment for more clarification or ask a question. Remember to subscribe to our newsletter to get the latest tutorial updates direct to your mailbox.

You may also like:

Leave a comment

Subscribe to get replies direct to your mailbox

Submit comment