Skip to main content

how to store data in SQLite database in android example


how
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

-MainActivity.java
-Contact.java
-DatabaseHandler.java

XML File

activity_main.XML

MainActivity.java

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


Contact.java

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


DatabaseHandler.java

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

activity_main.XML

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.

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App §   2.4.7  Set the color §   2.4.8  Adding Animations o    2.5  To plot grouped bar chart §   2.5.1  Creating Dataset o    2.6  Get the best of Android plus exclusive deals and freebies in your inbox!