The following tutorial is an illustration of saving data in the SQLite database in Android which automatically comes with Android OS. In this tutorial we are inserting some details of Employees in the database. Using SQLite is very easy because you don’t need to establish any connetion like JDBC and ODBC.

Steps Involved:

1. Create a xml file to create layout: activity_main.xml
2. Create a model class of an employee: EmployeeDetails
3. Create a class to handle the database operations which will inherit ‘SQLiteOpenHelper’: DatabaseHandler.java
4. Create a main activity class to call the database operations: MainActivity.java

Implementation of Steps Involved

Step 1: Create activity_main.xml in res/layout/

captue

<ScrollView xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”>

<RelativeLayout
android:layout_width=”match_parent”
android:layout_height=”match_parent”

android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”.MainActivity”>

<RelativeLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”40dp”
android:background=”#ffffff”
android:padding=”2dp”>
<TableLayout
android:id=”@+id/table”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:shrinkColumns=”*”
android:stretchColumns=”*”>

<TableRow
android:layout_width=”match_parent”
android:layout_height=”wrap_content”>

<TextView
android:layout_column=”0″
android:layout_span=”13″
android:background=”#ffffff”
android:gravity=”center”
android:paddingBottom=”20dp”
android:paddingTop=”20dp”
android:text=”EMPLOYEE DETAILS”
android:textColor=”#206009″
android:textSize=”30dp” />
</TableRow>
<TableRow
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”10dp”>

<TextView
android:id=”@+id/lbl_name”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_column=”0″
android:layout_marginLeft=”25dp”
android:text=”Name”
android:textSize=”18sp” />

<EditText
android:id=”@+id/editTextName”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_column=”4″
android:hint=”Enter Name Here”
android:singleLine=”true”
android:textColor=”#000000″ />

</TableRow>
<TableRow
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”10dp”>

<TextView
android:id=”@+id/lbl_age”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginLeft=”25dp”
android:text=”Age”
android:textSize=”18sp” />

<EditText
android:id=”@+id/editTextAge”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_column=”4″
android:layout_span=”2″
android:hint=”Enter Age Here”
android:singleLine=”true”
android:textColor=”#000000″ />

</TableRow>

<TableRow
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”10dp”>

<TextView
android:id=”@+id/lbl_empno”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginLeft=”25dp”
android:text=”Emp No”
android:textSize=”18sp” />

<EditText
android:id=”@+id/editTextEmpNumber”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_column=”4″
android:hint=”Enter Emp Number”
android:singleLine=”true”
android:textColor=”#000000″ />

</TableRow>

<TableRow
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”10dp”>

<Button
android:id=”@+id/btnSave”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_marginBottom=”20dp”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”17dp”
android:layout_span=”13″
android:text=”Save Data”
android:textColor=”#206009″ />

</TableRow>

<TableRow
android:layout_width=”match_parent”
android:layout_height=”wrap_content”>

<Button
android:id=”@+id/btnShow”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_marginBottom=”20dp”
android:layout_marginLeft=”20dp”
android:layout_marginRight=”20dp”
android:layout_marginTop=”17dp”
android:layout_span=”13″
android:text=”Show Data”
android:textColor=”#206009″ />

</TableRow>
</TableLayout>
</RelativeLayout>
</RelativeLayout>
</ScrollView>

Step 2: Create EmployeeDetails.java with getters and setters

public class EmployeeDetails {
String empName;
int empAge;
int empNumber;

//Default Constructor
public EmployeeDetails(){}

//Parameterised Constructor
public EmployeeDetails(String empName,int empAge,int empNumber){
this.empName = empName;
this.empAge = empAge;
this.empNumber = empNumber;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public int getEmpAge() {
return empAge;
}

public void setEmpAge(int empAge) {
this.empAge = empAge;
}

public int getEmpNumber() {
return empNumber;
}

public void setEmpNumber(int empNumber) {
this.empNumber = empNumber;
}
}

Step 3: Create a class to handle the database operations: DatabaseHandler.java
Important Notes: # This class must inherit SQLiteOpenHelper
# This class must override two methods
1. public void onCreate()
2. public void onUpgrade()

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;

import example.androidsubway.com.sqlitetutorial.model.EmployeeDetails;

public class DatabaseHandler extends SQLiteOpenHelper {

//Database Version
private static final int DATABASE_VERSION = 1;

//Database Name
private static final String DATABASE_NAME = “EmployeeData”;

//Table Name
private static final String TABLE_NAME = “Employee”;

//Table Columns names

private static final String EMP_NAME = “emp_name”;
private static final String EMP_AGE = “emp_age”;
private static final String EMP_NUMBER = “emp_number”;

public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

//Override onCreate() method – must do action
@Override
public void onCreate(SQLiteDatabase db) {

String createTableQuery = “CREATE TABLE ” + TABLE_NAME + “(” +
EMP_NAME + ” TEXT, ” + EMP_AGE + ” INTEGER, ” + EMP_NUMBER + ” INTEGER” + “)”;
db.execSQL(createTableQuery);
}

//Override onUpgrade()
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Commands related to upgrade the table contents ()
db.execSQL(“DROP TABLE IF EXITS ” + TABLE_NAME);
}
// Now all other CURD (Create, Update, Read, Delete)operations are below

// Add a new Employee Details
public void addEmployeeDetails(EmployeeDetails employeeDetails) {

SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(EMP_NAME, employeeDetails.getEmpName());
values.put(EMP_AGE, employeeDetails.getEmpAge());
values.put(EMP_NUMBER, employeeDetails.getEmpNumber());

db.insert(TABLE_NAME, null, values);
db.close();

}

//get the details of a single employee

public EmployeeDetails getSingleEmployeeDetails(int empNum) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{EMP_NAME, EMP_AGE, EMP_NUMBER}, EMP_NUMBER + “=?”,
new String[]{String.valueOf(empNum)}, null, null, null, null);

if (cursor != null) {
cursor.moveToFirst();
}
EmployeeDetails employeeDetails = new EmployeeDetails(cursor.getString(0), Integer.parseInt(cursor.getString(1)), Integer.parseInt(cursor.getString(2)));
return employeeDetails;
}

//get details of all employees

public List<EmployeeDetails> getAllEmployeeDetails() {
List<EmployeeDetails> employeeDetailsList = new ArrayList<EmployeeDetails>();
String selectQuery = “SELECT * FROM ” + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// Iterate the loop till cursor reaches the end
if (cursor.moveToFirst()) { // methods returns false if cursor is empty
do {
EmployeeDetails employeeDetails = new EmployeeDetails();
employeeDetails.setEmpName(cursor.getString(0));
employeeDetails.setEmpAge(Integer.parseInt(cursor.getString(1)));
employeeDetails.setEmpNumber(Integer.parseInt(cursor.getString(2)));

employeeDetailsList.add(employeeDetails);
} while (cursor.moveToNext());
}
return employeeDetailsList;
}

// Updating single employee details
public int updateEmployeeDetails(EmployeeDetails employeeDetails) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(EMP_NAME, employeeDetails.getEmpName());
values.put(EMP_AGE, employeeDetails.getEmpAge());

// update query
return db.update(TABLE_NAME, values, EMP_NUMBER + ” = ?”,
new String[]{String.valueOf(employeeDetails.getEmpNumber())});
}

//Deleting Employee Details
public void deleteEmployeeDetails(EmployeeDetails employeeDetails) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, EMP_NUMBER + ” = ?”,
new String[]{String.valueOf(employeeDetails.getEmpNumber())});
db.close();
}

public int getEmployeeCount() {
String countQuery = “SELECT * FROM ” + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
//cursor.close();
return cursor.getCount();
}

}
Step 4. Create a main activity class: MainActivity.java

Note: In this class we have 2 buttons one is ‘btnSave’ and another is ‘btnShow’
‘btnSave’ will insert the records in the database
‘btnShow’ will show all the inserted records in the Log/Logcat

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.List;

import example.androidsubway.com.sqlitetutorial.Handler.DatabaseHandler;
import example.androidsubway.com.sqlitetutorial.model.EmployeeDetails;

public class MainActivity extends AppCompatActivity {

EditText editTextName;
EditText editTextAge;
EditText editTextNumber;

Button btnSave, btnShow;

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

final DatabaseHandler databaseHandler = new DatabaseHandler(this);

editTextName = (EditText) findViewById(R.id.editTextName);
editTextAge = (EditText) findViewById(R.id.editTextAge);
editTextNumber = (EditText) findViewById(R.id.editTextEmpNumber);

btnSave = (Button) findViewById(R.id.btnSave);
btnShow = (Button) findViewById(R.id.btnShow);

btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EmployeeDetails employeeDetails = new EmployeeDetails();

employeeDetails.setEmpName(editTextName.getText().toString());
employeeDetails.setEmpAge(Integer.parseInt(editTextAge.getText().toString()));
employeeDetails.setEmpNumber(Integer.parseInt(editTextNumber.getText().toString()));

databaseHandler.addEmployeeDetails(employeeDetails);

editTextName.setText(“”);
editTextAge.setText(“”);
editTextNumber.setText(“”);
}

});

/**
* btnShow will print all the records of the Table
* In the Log OR Logcat
*/

btnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(“Reading”, “Reading the saved data”);
List<EmployeeDetails> employeeDetailsList = databaseHandler.getAllEmployeeDetails();
for (EmployeeDetails emp : employeeDetailsList) {
String log = “Name: ” + emp.getEmpName() + ” ,Age: ” + emp.getEmpAge() + ” , Number: ” + emp.getEmpNumber();
Log.d(“Record: “, log);
}
}
});

}
}

Advertisements