Android SQLite Database Insert Example

      
In this tutorial,we are going to learn how to insert data into Android SQLite.Here we are dealing with a intermediate part of Android Development.
Before continuing,we need to learn Android SQLite basic
       Here am going to insert first name, last name and email into a database named “Register”.Lets start how to implement it

STEP BY STEP

1.Create a Android Project

Refer:-How to create Android Project

2.Lets create interface.Here am using Android ADT with Android 4.2 Jellybean SDK.

Refer:-How to download and setup Android ADT

activity_main.xml

<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:gravity="center_vertical"
android:orientation="vertical" >

    <ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="343dp"
android:layout_weight="0.89"
android:src="@drawable/logo" />

    <Button
android:id="@+id/reg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="signIn"
android:text="Register"/>

   </LinearLayout>

The output of activity_main.xml is shown bellow

sqlite1

3.Next we need to create a registration form.The code is shown bellow.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_vertical" >

    <TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="USER REGISTRATION"
android:layout_marginLeft="60dp"
android:layout_marginBottom="20dp"
android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
android:id="@+id/editTextFirstname"
android:hint="Firstname"
android:layout_width="match_parent"
android:layout_height="wrap_content">

        <requestFocus />
</EditText>

<EditText
android:id="@+id/editTextLastname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Lastname"
/>

    <EditText
android:id="@+id/editTextEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Email"
/>

    <Button
android:id="@+id/registerbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="REGISTER"
android:layout_marginBottom="60dp" />

</LinearLayout>

The output of above is shown bellow

sqlite2

4.Next we need to create Activity file.

MainActivity.java

package com.example.mydatabase;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity
{
Button registerbutton;
RegisterAdapter register;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// create a instance of SQLite Database
register=new RegisterAdapter(this);
register=register.open();

// Get The Refference Of Buttons
registerbutton=(Button)findViewById(R.id.reg);

// Set OnClick Listener on SignUp button
registerbutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub

/// Create Intent for SignUpActivity  and Start The Activity
Intent registerintent=new Intent(getApplicationContext(),SignupActivity.class);
startActivity(registerintent);
}
});
}

@Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
register.close();
}
}

5.Next we need the activity class file for registration form

SignupActivity.java

package com.example.mydatabase;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SignupActivity extends Activity
{
EditText editTextFirstname,editTextLastname,editTextEmail;
Button btnregister;

RegisterAdapter register;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);

// get Instance  of Database Adapter
register=new RegisterAdapter(this);
register=register.open();

// Get Refferences of Views
editTextFirstname=(EditText)findViewById(R.id.editTextFirstname);
editTextLastname=(EditText)findViewById(R.id.editTextLastname);
editTextEmail=(EditText)findViewById(R.id.editTextEmail);

btnregister=(Button)findViewById(R.id.registerbutton);

btnregister.setOnClickListener(new View.OnClickListener()
{

public void onClick(View v) {
// TODO Auto-generated method stub

String userName=editTextFirstname.getText().toString();
String password=editTextLastname.getText().toString();
String confirmPassword=editTextEmail.getText().toString();

// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches

else
{
// Save the Data in Database
register.insertEntry(userName, password);
Toast.makeText(getApplicationContext(), "Registered Successfully ", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();

register.close();
}
}

6.Next we need to have DatabaseHelper java file

DataBaseHelper.java

package com.example.mydatabase;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
@Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(RegisterAdapter.DATABASE_CREATE);

}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");

// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}

7.Next we need a adapter class file

RegisterAdapter.java

package com.example.mydatabase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class RegisterAdapter
{
static final String DATABASE_NAME = "register.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"REGISTER"+
"( " +"ID"+" integer primary key autoincrement,"+ "FIRSTNAME text,LASTNAME text,EMAIL text); ";
// Variable to hold the database instanceSTER
public  SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public  RegisterAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public  RegisterAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}

        public  SQLiteDatabase getDatabaseInstance()
{
return db;
}

        public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);

// Insert the row into your table
db.insert("LOGIN", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void  updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);

String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
}

8.Lets run the android application

9.Output is shown bellow.

sqlite1

 

sqlite2

 

sqlite3

Now we need to check whether the data is insert or not.

So we click in the following.

Window—>Show Views—>Others—>Search for DDMS

From the opened DDMS window

Select File—>Select your package—>In that a register.db file is shown

 

So the data is inserted to Android SQLite

sqlite4

 

Hope you understand and comments please