Android ORMLite with SQLite Database Tutorial

This tutorial will guide you how to implement ORMLite (a very light weight, open source, Android compatible ORM) in an Android project and what are the benefits you may achieve compare to conventional way of using SQLite from Android. You will learn to build an app with ORMLite that allows you to store and view data from a database. So lets begin…


Tutorial

Requirements

The attached source code is a simple Android application named “StudentDirectory“, which will store the student records into the SQLite database along with its class teacher’s details. So, use cases of the applications are:

  1. Create Teacher record.
  2. Create Student record.
  3. View list of Students stored into the db.
  4. View list of Teachers stored into the db.

Application Screens

There are 6 screens in this application as described below:

MainActivity
Launcher screen of the app.

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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:layout_marginBottom="20dip"
        android:text="Student Directory"
        android:textSize="25sp" />

    <Button
        android:id="@+id/add_student_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:text="Add New Student" />

    <Button
        android:id="@+id/add_teacher_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:text="Add New Teacher" />

    <Button
        android:id="@+id/view_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:text="View Student Records" />

    <Button
        android:id="@+id/view_teacher_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:text="View Teacher Records" />

</LinearLayout>

 Output:

MainActivity-Student Directory

 

StudentAddActivity
To add a student record into the database.

activity_add_student.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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:text="Add New Student"
        android:textSize="25sp" />

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:orientation="vertical"
        android:padding="10dip" >

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

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dip"
                android:text="Student Name "
                android:textSize="15sp" />

            <EditText
                android:id="@+id/student_name_et"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dip"
                android:layout_weight="1"
                android:inputType="text" />
        </TableRow>

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

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dip"
                android:text="Address "
                android:textSize="15sp" />

            <EditText
                android:id="@+id/address_et"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dip"
                android:layout_weight="1"
                android:inputType="text" />
        </TableRow>

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

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dip"
                android:text="Class Teacher Name"
                android:textSize="15sp" />

            <Spinner
                android:id="@+id/teacher_sp"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dip"
                android:layout_weight="2" />
        </TableRow>
    </TableLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="20dip" >

        <Button
            android:id="@+id/reset_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_weight="1"
            android:text="Reset" />

        <Button
            android:id="@+id/submit_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_weight="1"
            android:text="Submit" />
    </LinearLayout>

</LinearLayout>

Output :

Add Student Screenshot

 

TeacherAddActivity
To add teacher record into the database.

activity_add_teacher.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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:text="Add New Teacher"
        android:textSize="25sp" />

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:orientation="vertical"
        android:padding="10dip" >

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

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dip"
                android:text="Teacher Name "
                android:textSize="15sp" />

            <EditText
                android:id="@+id/teacher_name_et"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dip"
                android:layout_weight="1"
                android:inputType="text" />
        </TableRow>

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

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dip"
                android:text="Address "
                android:textSize="15sp" />

            <EditText
                android:id="@+id/address_et"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dip"
                android:layout_weight="1"
                android:inputType="text" />
        </TableRow>
    </TableLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="20dip" >

        <Button
            android:id="@+id/reset_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_weight="1"
            android:text="Reset" />

        <Button
            android:id="@+id/submit_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_weight="1"
            android:text="Submit" />
    </LinearLayout>

</LinearLayout>

Output :

Add Teacher Screenshot

 

ViewStudentRecordActivity and ViewTeacherRecordActivity
To display the list of student and teacher records stored into the database. Both activity share the same graphical xml file.

activity_view_recd.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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:id="@+id/header_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:text="View Student Records"
        android:textSize="25sp" />

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dip" >

        <ListView
            android:id="@+id/listview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </TableLayout>

</LinearLayout>

list_item.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:orientation="horizontal" >

    <TableRow
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#6f6c67" >

        <TextView
            android:id="@+id/student_name_tv"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_margin="1dip"
            android:layout_marginTop="10dip"
            android:layout_weight="1"
            android:background="#fff"
            android:gravity="center"
            android:padding="3dip"
            android:text="Student Name "
            android:textSize="15sp" />

        <TextView
            android:id="@+id/teacher_tv"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_margin="1dip"
            android:layout_marginTop="10dip"
            android:layout_weight="1"
            android:background="#fff"
            android:gravity="center"
            android:padding="3dip"
            android:text="Class Teacher Name "
            android:textSize="15sp" />
    </TableRow>

</LinearLayout>

Output :

View Student Records

Output :

View Teacher Records

 

ViewTeacherDetailsActivity
To display the details of a selected teacher from the previous screen.

activity_view_teacher.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:orientation="vertical" >

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:orientation="vertical"
        android:padding="10dip" >

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Teacher Name : "
                android:textSize="15sp" />

            <TextView
                android:id="@+id/teacher_name_et"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dip"
                android:layout_marginRight="20dip"
                android:layout_weight="1"
                android:enabled="false"
                android:inputType="text" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Address : "
                android:textSize="15sp" />

            <TextView
                android:id="@+id/address_et"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dip"
                android:layout_marginRight="20dip"
                android:layout_weight="1"
                android:enabled="false"
                android:inputType="text" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Students :"
                android:textSize="15sp" />

            <TextView
                android:id="@+id/students_et"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dip"
                android:layout_marginRight="20dip"
                android:layout_weight="1"
                android:enabled="false"
                android:inputType="text" />
        </TableRow>
    </TableLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="20dip" >

        <Button
            android:id="@+id/close_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_weight="1"
            android:text="Close" />
    </LinearLayout>

</LinearLayout>

Output :

View Teacher Detail Records

Steps to Implement ORMLite into Android Project

1.      Download and Include the Libraries

You would need two additional libraries apart from Android support library and those are:

  • ormlite-android-x.jar
  • ormlite-core-x.jar

You may download the latest copies either from the libs directory of the attached source code or from the below URL:

http://sourceforge.net/projects/ormlite/files/releases/com/j256/ormlite/

You may download both of them and put into the “libs” directory of the project.

2.      Database Table structure

We have two tables in our application: teacher_details and student_details.  Table student_details contains a foreign key mapping to table teacher_details as shown below:

student_details

student_idint (auto) –  PK
student_nameString
addressString
added_dateDate
teacher_idInt – FK

teacher_details

teacher_idint (auto) –  PK
teacher_nameString
addressString

3.      Data Models

There are two data model class, one each for two tables: TeacherDetails and StudentDetails.

To create an auto generated integer type primary key, you have write code like:

@DatabaseField(generatedId = true, columnName = "teacher_id")
public int teacherId;

Where, columnName maps actual column name of the database table, in case you have different names for database field and Java model object (here in database it is teacher_id but in Java model class teacherId)

To create a foreign key mapping, you have to write code like:

@DatabaseField(canBeNull = false, foreign = true, foreignAutoRefresh = true)
public TeacherDetails teacher;

The following code is the TeacherDetails class:

TeacherDetails.java

package com.androidbegin.studentdirectory.data;

import java.io.Serializable;
import com.j256.ormlite.field.DatabaseField;

public class TeacherDetails implements Serializable {

	/**
	 *  Model class for teacher_details database table
	 */
	private static final long serialVersionUID = -222864131214757024L;
	
	// Primary key defined as an auto generated integer 
	// If the database table column name differs than the Model class variable name, the way to map to use columnName
	@DatabaseField(generatedId = true, columnName = "teacher_id")
	public int teacherId;

	// Define a String type field to hold teacher's name
	@DatabaseField(columnName = "teacher_name")
	public String teacherName;
	
	// Define a String type field to hold student's address
	public String address;
	
	// Default constructor is needed for the SQLite, so make sure you also have it
	public TeacherDetails(){
		
	}
	
	//For our own purpose, so it's easier to create a TeacherDetails object
	public TeacherDetails(final String name, final String address){
		this.teacherName = name;
		this.address = address;
	}
}

The following code is the StudentDetails class:

StudentDetails.java

package com.androidbegin.studentdirectory.data;

import java.io.Serializable;
import java.util.Date;
import com.j256.ormlite.field.DatabaseField;

public class StudentDetails implements Serializable {

	/**
	 * Model class for student_details database table
	 */
	private static final long serialVersionUID = -222864131214757024L;
	
	public static final String ID_FIELD = "student_id";
	public static final String TEACHER_ID_FIELD = "teacher_id";
	
	// Primary key defined as an auto generated integer 
	// If the database table column name differs than the Model class variable name, the way to map to use columnName
	@DatabaseField(generatedId = true, columnName = ID_FIELD)
	public int studentId;

	// Define a String type field to hold student's name
	@DatabaseField(columnName = "student_name")
	public String studentName;
	
	// Define a String type field to hold student's address
	public String address;
	
	// Foreign key defined to hold associations
	@DatabaseField(canBeNull = false, foreign = true, foreignAutoRefresh = true)
	public TeacherDetails teacher;
	
	// Define a String type field to hold student's date of insertion
	@DatabaseField(columnName = "added_date")
	public Date addedDate;
	
	// Default constructor is needed for the SQLite, so make sure you also have it
	public StudentDetails(){
		
	}
	
	//For our own purpose, so it's easier to create a StudentDetails object
	public StudentDetails(final String name, final String address, TeacherDetails teacher){
		this.studentName = name;
		this.address = address;
		this.teacher = teacher;
	}

}

 

4.      ORMLite Configuration file

ormlite_config.txt  – This is the .txt file which has been kept in res/raw directory. This configuration file should include every details such as the bin file name (with package), both fieldName as well as columnName, information regarding foreign key (as described in the sample app) etc.

ormlite_config.txt

# --table-start--
dataClass=com.androidbegin.studentdirectory.data.TeacherDetails
tableName=teacher_details
# --table-fields-start--
# --field-start--
fieldName=teacherId
columnName=teacher_id
generatedId=true
# --field-end--
# --field-start--
fieldName=teacherName
columnName=teacher_name
# --field-end--
# --field-start--
fieldName=address
# --field-end--
# --table-fields-end--
# --table-end--
#################################

#################################
# --table-start--
dataClass=com.androidbegin.studentdirectory.data.StudentDetails
tableName=student_details
# --table-fields-start--
# --field-start--
fieldName=studentId
columnName=student_id
generatedId=true
# --field-end--
# --field-start--
fieldName=studentName
columnName=student_name
# --field-end--
# --field-start--
fieldName=address
# --field-end--
# --field-start--
fieldName=addedDate
columnName=added_date
# --field-end--
# --field-start--
fieldName=teacher
columnName=teacher_id
foreign=true
# --field-end--
# --table-fields-end--
# --table-end--
#################################

 

DatabaseConfigUtil.java

package com.androidbegin.studentdirectory.data;

import java.io.IOException;
import java.sql.SQLException;
import com.j256.ormlite.android.apptools.OrmLiteConfigUtil;


public class DatabaseConfigUtil extends OrmLiteConfigUtil {

	public static void main(String[] args) throws SQLException, IOException {
		
		// Provide the name of .txt file which you have already created and kept in res/raw directory
		writeConfigFile("ormlite_config.txt");
	}
}

 

5.      Database Helper

It is the most important file from the ORMLite implementation point of view, which consists the complete logic of database file creation, accessibility etc. Below are the key points of this file:

  • Database Name & version: Keep the database name and version as shown in the example.
  • onCreate(): This method should include all the table creation statements and other first time configuration logics.
  • onUpgrade(): onCreate() method executes only once i.e. when the application is running for the first time, so in case application needs any update in the database (e.g. creation of new table, insertion of a new column in an existing table etc.), this method needs to incorporate all those logics, so application doesn’t crash after getting upgraded.
  • DAO: DAOs are the one of the most important components in ORMLite ecosystem as those are the only handle to access database tables. So, every table should expose a DAO, so application can access this table when required.

DatabaseHelper.java

package com.androidbegin.studentdirectory.data;

import java.sql.SQLException;

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

import com.androidbegin.studentdirectory.R;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

/**
 * Database helper which creates and upgrades the database and provides the DAOs for the app.
 * 
 * 
 */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	/************************************************
	 * Suggested Copy/Paste code. Everything from here to the done block.
	 ************************************************/

	private static final String DATABASE_NAME = "studentdir.db";
	private static final int DATABASE_VERSION = 1; 

	private Dao<StudentDetails, Integer> studentDao;
	private Dao<TeacherDetails, Integer> teacherDao;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
	}

	/************************************************
	 * Suggested Copy/Paste Done
	 ************************************************/

	@Override
	public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
		try {
			
			// Create tables. This onCreate() method will be invoked only once of the application life time i.e. the first time when the application starts.
			TableUtils.createTable(connectionSource, TeacherDetails.class);
			TableUtils.createTable(connectionSource, StudentDetails.class);
			
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVer, int newVer) {
		try {
			
			// In case of change in database of next version of application, please increase the value of DATABASE_VERSION variable, then this method will be invoked 
			//automatically. Developer needs to handle the upgrade logic here, i.e. create a new table or a new column to an existing table, take the backups of the
			// existing database etc.
			
			TableUtils.dropTable(connectionSource, TeacherDetails.class, true);
			TableUtils.dropTable(connectionSource, StudentDetails.class, true);
			onCreate(sqliteDatabase, connectionSource);
			
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Unable to upgrade database from version " + oldVer + " to new "
					+ newVer, e);
		}
	}
	
	// Create the getDao methods of all database tables to access those from android code.
	// Insert, delete, read, update everything will be happened through DAOs

	public Dao<TeacherDetails, Integer> getTeacherDao() throws SQLException {
		if (teacherDao == null) {
			teacherDao = getDao(TeacherDetails.class);
		}
		return teacherDao;
	}

	public Dao<StudentDetails, Integer> getStudentDao() throws SQLException {
		if (studentDao == null) {
			studentDao = getDao(StudentDetails.class);
		}
		return studentDao;
	}
}

6.      TeacherAddActivity

  • Reference of DatabaseHelper – As I mentioned earlier, we can interact to SQLite database only through the DAOs which are the part of DatatabaseHelper, so getting a reference of the same is the next thing to do.
  • Create TeacherDetails object and insert into DB – Next, is the get the user inputs from the Screen and insert the record into the database. You may write the code like:

TeacherAddActivity.java

package com.androidbegin.studentdirectory;

import java.sql.SQLException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.androidbegin.studentdirectory.data.DatabaseHelper;
import com.androidbegin.studentdirectory.data.TeacherDetails;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

public class TeacherAddActivity extends Activity implements OnClickListener {

	// Reference of DatabaseHelper class to access its DAOs and other components
	private DatabaseHelper databaseHelper = null;
	
	private EditText teacher_name_et, address_et;
	private Button reset_btn, submit_btn;

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

		teacher_name_et = (EditText) findViewById(R.id.teacher_name_et);
		address_et = (EditText) findViewById(R.id.address_et);
		reset_btn = (Button) findViewById(R.id.reset_btn);
		submit_btn = (Button) findViewById(R.id.submit_btn);
		
		reset_btn.setOnClickListener(this);
		submit_btn.setOnClickListener(this);
	}

	// This is how, DatabaseHelper can be initialized for future use
	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this,DatabaseHelper.class);
		}
		return databaseHelper;
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();

		/*
		 * You'll need this in your class to release the helper when done.
		 */
		if (databaseHelper != null) {
			OpenHelperManager.releaseHelper();
			databaseHelper = null;
		}
	}
	
	@Override
	public void onClick(View v) {

		if(v == submit_btn)
		{
			// All input fields are mandatory, so made a check
			if(teacher_name_et.getText().toString().trim().length() > 0 && 
									address_et.getText().toString().trim().length() > 0)
			{
				// Once click on "Submit", it's first creates the TeacherDetails object
				final TeacherDetails techDetails = new TeacherDetails();
				
				// Then, set all the values from user input
				techDetails.teacherName = teacher_name_et.getText().toString();
				techDetails.address = address_et.getText().toString();
				
				try {
					// This is how, a reference of DAO object can be done
					final Dao<TeacherDetails, Integer> techerDao = getHelper().getTeacherDao();
					
					//This is the way to insert data into a database table 
					techerDao.create(techDetails);
					reset();
					showDialog();
					
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			// Show a dialog with appropriate message in case input fields are blank
			else
			{
				showMessageDialog("All fields are mandatory !!");
			}
		}
		else if(v == reset_btn)
		{
			reset();
		}
	}
	
	private void showMessageDialog(final String message)
	{
		final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setMessage(message);
		final AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
	
	// Clear the entered text
	private void reset()
	{
		teacher_name_et.setText("");
		address_et.setText("");
	}
	
	private void showDialog()
	{
		// After submission, Dialog opens up with "Success" message. So, build the AlartBox first
		final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		
		// Set the appropriate message into it.
		alertDialogBuilder.setMessage("Teacher record added successfully !!");
		
		// Add a positive button and it's action. In our case action would be, just hide the dialog box , 
		// so no need to write any code for that.
		alertDialogBuilder.setPositiveButton("Add More",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						//finish();
					}
				});
		
		// Add a negative button and it's action. In our case, just open up the ViewTeacherRecordActivity screen 
		// to display all the records
		alertDialogBuilder.setNegativeButton("View Records",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent negativeActivity = new Intent(getApplicationContext(),ViewTeacherRecordActivity.class);
						startActivity(negativeActivity);
						finish();
					}
				});

		// Now, create the Dialog and show it.
		final AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
}

 

7.      StudentAddActivity

  • Fetch Teacher Records – Because every student must associate a teacher, so it’s required to provide a selection option of the “Teacher” for every student and hence the fetch of “TeacherDetails” records from the database table.
  • Populate Teacher Spinner – To select a teacher from the teacher list, here I used a spinner with CustomAdapter.
  • Create StudentDetails object and insert into DB – Next, is the get the user inputs from the Screen and insert the record into the database. You may write the code like:

StudentAddActivity.java

package com.androidbegin.studentdirectory;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.androidbegin.studentdirectory.data.DatabaseHelper;
import com.androidbegin.studentdirectory.data.StudentDetails;
import com.androidbegin.studentdirectory.data.TeacherDetails;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

public class StudentAddActivity extends Activity implements OnClickListener {

	// Reference of DatabaseHelper class to access its DAOs and other components
	private DatabaseHelper databaseHelper = null;

	// Declaration of screen components
	private EditText student_name_et, address_et;
	private Button reset_btn, submit_btn;
	private Spinner teacher_sp;
	
	// This object would hold the list of all teachers, so user can select a particular one to associate with a student
	private List<TeacherDetails> teacherList;

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

		student_name_et = (EditText) findViewById(R.id.student_name_et);
		address_et = (EditText) findViewById(R.id.address_et);
		teacher_sp = (Spinner) findViewById(R.id.teacher_sp);
		reset_btn = (Button) findViewById(R.id.reset_btn);
		submit_btn = (Button) findViewById(R.id.submit_btn);
		
		try {
			// This is how, a reference of DAO object can be done
			// Need to find out list of TeacherDetails from database, so initialize DAO for TeacherDetails first
			final Dao<TeacherDetails, Integer> teachDao = getHelper().getTeacherDao();
			
			// Query the database. We need all the records so, used queryForAll()
			teacherList = teachDao.queryForAll();
			
			// Populate the spinner with Teachers data by using CustomAdapter
			teacher_sp.setAdapter(new CustomAdapter(this,android.R.layout.simple_spinner_item, android.R.layout.simple_spinner_dropdown_item, teacherList));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		reset_btn.setOnClickListener(this);
		submit_btn.setOnClickListener(this);
	}

	// This is how, DatabaseHelper can be initialized for future use
	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this,DatabaseHelper.class);
		}
		return databaseHelper;
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();

		/*
		 * You'll need this in your class to release the helper when done.
		 */
		if (databaseHelper != null) {
			OpenHelperManager.releaseHelper();
			databaseHelper = null;
		}
	}
	
	@Override
	public void onClick(View v) {

		if(v == submit_btn)
		{
			// Student Details record only be added, if atleast one Teacher Details data exists in the database
			if(teacherList.size() > 0)
			{
				// All input fields are mandatory, so made a check 
				if(student_name_et.getText().toString().trim().length() > 0 && 
										address_et.getText().toString().trim().length() > 0)
				{
					// Create the StudentDetails object and set the inputed data into it
					final StudentDetails stuDetails = new StudentDetails();
					stuDetails.studentName = student_name_et.getText().toString();
					stuDetails.address = address_et.getText().toString();
					stuDetails.addedDate = new Date();
					
					// StudentDetails has a reference to TeacherDetails, so set the reference as well
					stuDetails.teacher =  (TeacherDetails) teacher_sp.getSelectedItem();
					
					try {
						// Now, need to interact with StudentDetails table/object, so initialize DAO for that
						final Dao<StudentDetails, Integer> studentDao = getHelper().getStudentDao();
						
						//This is the way to insert data into a database table 
						studentDao.create(stuDetails);
						reset();
						showDialog();
						
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				// Show a dialog with appropriate message in case input fields are blank
				else
				{
					showMessageDialog("All fields are mandatory !!");
				}
			}
			// If no TeacherDetails data found in the database, show a dialog with appropriate message to user
			else
			{
				showMessageDialog("Please, add Teacher Details first !!");
			}
		}
		else if(v == reset_btn)
		{
			reset();
		}
	}
	
	private void showMessageDialog(final String message)
	{
		final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setMessage(message);
		final AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
	
	// Clear the entered text
	private void reset()
	{
		student_name_et.setText("");
		address_et.setText("");
	}
	
	private void showDialog()
	{
		// After submission, Dialog opens up with "Success" message. So, build the AlartBox first
		final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		
		// Set the appropriate message into it.
		alertDialogBuilder.setMessage("Student record added successfully !!");
		
		// Add a positive button and it's action. In our case action would be, just hide the dialog box
		// so no need to write any code for that.
		alertDialogBuilder.setPositiveButton("Add More",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
					}
				});
		
		// Add a negative button and it's action. In our case, just open up the ViewStudentRecordActivity screen 
		//to display all the records
		alertDialogBuilder.setNegativeButton("View Records",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						final Intent negativeActivity = new Intent(getApplicationContext(),ViewStudentRecordActivity.class);
						startActivity(negativeActivity);
						finish();
					}
				});

		// Now, create the Dialog and show it.
		final AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
	
	// Custom Adapter to feed data to the Teacher Spinner
	@SuppressWarnings("rawtypes")
	class CustomAdapter extends ArrayAdapter<String>
	{
		LayoutInflater inflater;
		
		// Holds data of Teacher Details
		List objects;
		
		@SuppressWarnings("unchecked")
		public CustomAdapter(Context context, int resource, int dropDownViewResource, List objects) {
			super(context, resource, objects);
			this.setDropDownViewResource(dropDownViewResource);
			inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
			// set the Teacher Details objects to populate the Spinner 
			this.objects = objects;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return getCustomView(position, convertView, parent);
		}
		
		@Override
		public View getDropDownView(int position, View convertView,ViewGroup parent) {
			return getCustomView(position, convertView, parent);
		}
		
		// Inflate the Android default spinner layout view, set the label according to passed data and 
		// return the view to display as one row of the Teacher Spinner
		public View getCustomView(int position, View convertView, ViewGroup parent) {
			
			final View row = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
			
			final TextView label = (TextView) row.findViewById(android.R.id.text1);
			final TeacherDetails teacher = (TeacherDetails) this.objects.get(position);
    		label.setText(teacher.teacherName);
			return row;
		}
	}
}

8.      ViewStudentRecordActivity

  • Fetch Student Records from Database
  • Delete a selected row – To delete a student record, you need to long press the particular row and proceed.

ViewStudentRecordActivit.java

package com.androidbegin.studentdirectory;


import java.sql.SQLException;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.androidbegin.studentdirectory.data.DatabaseHelper;
import com.androidbegin.studentdirectory.data.StudentDetails;
import com.androidbegin.studentdirectory.data.TeacherDetails;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

public class ViewStudentRecordActivity extends Activity implements OnItemClickListener, OnItemLongClickListener {

	// Reference of DatabaseHelper class to access its DAOs and other components
	private DatabaseHelper databaseHelper = null;
	
	// This ListView displays the list of Student Details data fetched from database.
	private ListView listview;
	
	// This holds the value of the row number, which user has selected for further action
	private int selectedRecordPosition = -1;
	
	// Declaration of DAOs to interact with corresponding table
	private Dao<TeacherDetails, Integer> techerDao;
	private Dao<StudentDetails, Integer> studentDao;
	
	// It holds the list of StudentDetails objects fetched from Database
	private List<StudentDetails> studentList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_recd);
		listview = (ListView) findViewById(R.id.listview);
		
		try {
			// This is how, a reference of DAO object can be done
			techerDao =  getHelper().getTeacherDao();
			studentDao =  getHelper().getStudentDao();
			
			// Query the database. We need all the records so, used queryForAll()
			studentList = studentDao.queryForAll();
			
			// Set the header of the ListView
			final LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View rowView = inflater.inflate(R.layout.list_item, listview, false);
			listview.addHeaderView(rowView);
			
			//Now, link the  RecordArrayAdapter with the ListView 
			listview.setAdapter(new RecordArrayAdapter(this, R.layout.list_item, studentList, techerDao));
			
			// Attach OnItemLongClickListener and OnItemClickListener to track user action and perform accordingly
			listview.setOnItemLongClickListener(this);
			listview.setOnItemClickListener(this);
			
			// If, no record found in the database, appropriate message needs to be displayed.
			populateNoRecordMsg();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void populateNoRecordMsg()
	{
		// If, no record found in the database, appropriate message needs to be displayed.
		if(studentList.size() == 0)
		{
			final TextView tv = new TextView(this);
			tv.setPadding(5, 5, 5, 5);
			tv.setTextSize(15);
			tv.setText("No Record Found !!");
			listview.addFooterView(tv);
		}
	}
	
	// This is how, DatabaseHelper can be initialized for future use
	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
		}
		return databaseHelper;
	}

	
	@Override
	protected void onDestroy() {
		super.onDestroy();

		/*
		 * You'll need this in your class to release the helper when done.
		 */
		if (databaseHelper != null) {
			OpenHelperManager.releaseHelper();
			databaseHelper = null;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if(position > 0)
		{
			// Details screen showing code can put over here
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position,long id) {
		
		// If the pressed row is not a header, update selectedRecordPosition and show dialog for further selection
		if(position > 0)
		{
			selectedRecordPosition = position - 1;
			showDialog();
		}
		return true;
	}
	
	private void showDialog()
	{
		// Before deletion of the long pressed record, need to confirm with the user. So, build the AlartBox first
		final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		
		// Set the appropriate message into it.
		alertDialogBuilder.setMessage("Are you Really want to delete the selected record ?");
		
		// Add a positive button and it's action. In our case action would be deletion of the data
		alertDialogBuilder.setPositiveButton("Delete",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						try {
							// This is how, data from the database can be deleted
							studentDao.delete(studentList.get(selectedRecordPosition));
							
							// Removing the same from the List to remove from display as well
							studentList.remove(selectedRecordPosition);
							listview.invalidateViews();
							
							// Reset the value of selectedRecordPosition
							selectedRecordPosition = -1;
							populateNoRecordMsg();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
		
		// Add a negative button and it's action. In our case, just hide the dialog box
		alertDialogBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});

		// Now, create the Dialog and show it.
		final AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
}

9.      ViewTeacherRecordActivity

  • Fetch Teacher Records from Database
  • Delete a selected row – To delete a teacher record, you need to long press the particular row and proceed.
  • View Teacher Details – To view the teacher details i.e. the students associated for a selected teacher, you need to tap on the particular row. You may write the code like:

ViewTeacherRecordActivit.java

package com.androidbegin.studentdirectory;


import java.sql.SQLException;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.androidbegin.studentdirectory.data.DatabaseHelper;
import com.androidbegin.studentdirectory.data.TeacherDetails;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

public class ViewTeacherRecordActivity extends Activity implements OnItemClickListener, OnItemLongClickListener {

	// Reference of DatabaseHelper class to access its DAOs and other components
	private DatabaseHelper databaseHelper = null;
	
	// This ListView displays the list of Teacher Details data fetched from database.
	private ListView listview;
	
	// This holds the value of the row number, which user has selected for further action
	private int selectedRecordPosition = -1;
	
	// Declaration of DAO to interact with corresponding table
	private Dao<TeacherDetails, Integer> teacherDao;
	
	// It holds the list of TeacherDetails object fetched from Database
	private List<TeacherDetails> teacherList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_recd);
		listview = (ListView) findViewById(R.id.listview);
		
		((TextView)findViewById(R.id.header_tv)).setText("View Teacher Records");
		
		try {
			// This is how, a reference of DAO object can be done
			teacherDao =  getHelper().getTeacherDao();
			
			// Query the database. We need all the records so, used queryForAll()
			teacherList = teacherDao.queryForAll();
			
			// Set the header of the ListView
			final LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View rowView = inflater.inflate(R.layout.list_item, listview, false);
			((TextView)rowView.findViewById(R.id.teacher_tv)).setText("Address");
			((TextView)rowView.findViewById(R.id.student_name_tv)).setText("Teacher Name");
			listview.addHeaderView(rowView);
			
			//Now, link the  RecordArrayAdapter with the ListView
			listview.setAdapter(new RecordArrayAdapter(this, R.layout.list_item, teacherList, teacherDao));
			
			// Attach OnItemLongClickListener and OnItemClickListener to track user action and perform accordingly
			listview.setOnItemLongClickListener(this);
			listview.setOnItemClickListener(this);
			
			// If, no record found in the database, appropriate message needs to be displayed.
			populateNoRecordMsg();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void populateNoRecordMsg()
	{
		// If, no record found in the database, appropriate message needs to be displayed.
		if(teacherList.size() == 0)
		{
			final TextView tv = new TextView(this);
			tv.setPadding(5, 5, 5, 5);
			tv.setTextSize(15);
			tv.setText("No Record Found !!");
			listview.addFooterView(tv);
		}
	}
	
	// This is how, DatabaseHelper can be initialized for future use
	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
		}
		return databaseHelper;
	}

	
	@Override
	protected void onDestroy() {
		super.onDestroy();

		/*
		 * You'll need this in your class to release the helper when done.
		 */
		if (databaseHelper != null) {
			OpenHelperManager.releaseHelper();
			databaseHelper = null;
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// If the pressed row is not a header, update selectedRecordPosition and render ViewTeacherDetailsActivity screen
		if(position > 0)
		{
			selectedRecordPosition = position - 1;
			// Details screen showing code can put over here
			final Intent intent = new Intent(this, ViewTeacherDetailsActivity.class);
			intent.putExtra("details",teacherList.get(selectedRecordPosition));
			startActivity(intent);
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position,long id) {
		
		// If the long pressed row is not a header, update selectedRecordPosition and show the dialog
		if(position > 0)
		{
			selectedRecordPosition = position - 1;
			showDialog();
		}
		return true;
	}
	
	private void showDialog()
	{
		// Before deletion of the long pressed record, need to confirm with the user. So, build the AlartBox first
		final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		
		// Set the appropriate message into it.
		alertDialogBuilder.setMessage("Are you Really want to delete the selected record ?");
		
		// Add a positive button and it's action. In our case action would be deletion of the data
		alertDialogBuilder.setPositiveButton("Delete",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						try {
							// This is how, data from the database can be deleted
							teacherDao.delete(teacherList.get(selectedRecordPosition));
							
							// Removing the same from the List to remove from display as well
							teacherList.remove(selectedRecordPosition);
							listview.invalidateViews();
							
							// Reset the value of selectedRecordPosition
							selectedRecordPosition = -1;
							populateNoRecordMsg();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
		// Add a negative button and it's action. In our case, just hide the dialog box
		alertDialogBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});

		// Now, create the Dialog and show it.
		final AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
}

 

10.      ViewTeacherDetailsActivity

  • Get Teacher Data from Intent – First, you need to receive the “Serializable” data, which we passed from the previous screen.
  • Build and prepare the query – Next, is to fetch the students data for the selected Teacher and we need to build and prepare a query for the same.
  • Fetch only matching Student Records from Database – You may write the code like:

ViewTeacherDetailsActivity.java

package com.androidbegin.studentdirectory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.androidbegin.studentdirectory.data.DatabaseHelper;
import com.androidbegin.studentdirectory.data.StudentDetails;
import com.androidbegin.studentdirectory.data.TeacherDetails;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

public class ViewTeacherDetailsActivity extends Activity implements OnClickListener {

	// Reference of DatabaseHelper class to access its DAOs and other components
	private DatabaseHelper databaseHelper = null;

	// Declaration of screen components
	private TextView teacher_name_et, address_et, students_et;
	private Button close_btn;
	
	// Declaration of DAO to interact with corresponding table
	private Dao<StudentDetails, Integer> studentDao;

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

		teacher_name_et = (TextView) findViewById(R.id.teacher_name_et);
		address_et = (TextView) findViewById(R.id.address_et);
		students_et = (TextView) findViewById(R.id.students_et);
		close_btn = (Button) findViewById(R.id.close_btn);
		
		close_btn.setOnClickListener(this);
		
		//Receive the TeacherDetails object which has sent by the previous screen through Intent
		final TeacherDetails tDetails = (TeacherDetails) getIntent().getExtras().getSerializable("details");
		
		teacher_name_et.setText(tDetails.teacherName);
		address_et.setText(tDetails.address);
		
		// This String would hold the list of all associated student's name (comma separated) for the selected Teacher 
		final List<String> studentName = new ArrayList<String>();
		
		try {
			// This is how, a reference of DAO object can be done
			studentDao =  getHelper().getStudentDao();
			
			// Get our query builder from the DAO
			final QueryBuilder<StudentDetails, Integer> queryBuilder = studentDao.queryBuilder();
			
			// We need only Students who are associated with the selected Teacher, so build the query by "Where" clause
			queryBuilder.where().eq(StudentDetails.TEACHER_ID_FIELD, tDetails.teacherId);
			
			// Prepare our SQL statement
			final PreparedQuery<StudentDetails> preparedQuery = queryBuilder.prepare();
			
			// Fetch the list from Database by queryingit 
			final Iterator<StudentDetails>  studentsIt = studentDao.query(preparedQuery).iterator();
			
			// Iterate through the StudentDetails object iterator and populate the comma separated String
			while (studentsIt.hasNext()) {
				final StudentDetails sDetails = studentsIt.next();
				studentName.add(sDetails.studentName);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		students_et.setText(studentName.toString());
	}

	// This is how, DatabaseHelper can be initialized for future use
	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this,DatabaseHelper.class);
		}
		return databaseHelper;
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();

		/*
		 * You'll need this in your class to release the helper when done.
		 */
		if (databaseHelper != null) {
			OpenHelperManager.releaseHelper();
			databaseHelper = null;
		}
	}
	
	@Override
	public void onClick(View v) {

		if(v == close_btn){
			finish();
		}
		
	}
}

 

11.     MainActivity

Created four buttons to access the appropriate classes.

MainActivity.java

package com.androidbegin.studentdirectory;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity implements OnClickListener {

	// Declaration all four buttons of the Main screen
	private Button add_student_btn, add_teacher_btn, view_btn, view_teacher_btn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// Initialization of all four buttons of the Main screen
		add_student_btn = (Button) findViewById(R.id.add_student_btn);
		add_teacher_btn = (Button) findViewById(R.id.add_teacher_btn);
		view_btn = (Button) findViewById(R.id.view_btn);
		view_teacher_btn = (Button) findViewById(R.id.view_teacher_btn);
		
		// Attachment of onClickListner for them
		add_student_btn.setOnClickListener(this);
		add_teacher_btn.setOnClickListener(this);
		view_btn.setOnClickListener(this);
		view_teacher_btn.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {

		// Render StudentAddActivity screen once click on "Add Student" Button
		Log.v("abc", "" + v);
		if(v == add_student_btn) {
			startActivity(new Intent(this, StudentAddActivity.class));
		}
		// Render TeacherAddActivity screen once click on "Add Teacher" Button
		else if(v == add_teacher_btn) {
			startActivity(new Intent(this, TeacherAddActivity.class));
		}
		// Render ViewStudentRecordActivity screen once click on "View Student Records" Button
		else if(v == view_btn) {
			startActivity(new Intent(this, ViewStudentRecordActivity.class));
		}
		// Render ViewTeacherRecordActivity screen once click on "View Teacher Records" Button
		else if(v == view_teacher_btn) {
			startActivity(new Intent(this, ViewTeacherRecordActivity.class));
		}
	}
}

 

12.      RecordArrayAdapter

An array adapter for the List View.

RecordArrayAdapte.java

package com.androidbegin.studentdirectory;

import java.util.List;

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 com.androidbegin.studentdirectory.data.StudentDetails;
import com.androidbegin.studentdirectory.data.TeacherDetails;
import com.j256.ormlite.dao.Dao;

@SuppressWarnings("rawtypes")
public class RecordArrayAdapter extends ArrayAdapter<String> {

		private LayoutInflater inflater;
		
		// This would hold the database objects. It could be TeacherDetails or StudentDetails objects
		private List records;
		
		// Declaration of DAO to interact with corresponding table
		private Dao<TeacherDetails, Integer> teacherDao;
		
		@SuppressWarnings("unchecked")
		public RecordArrayAdapter(Context context, int resource, List objects, Dao<TeacherDetails, Integer> teacherDao) {
			super(context, resource, objects);
			
			this.records = objects;
			this.teacherDao = teacherDao;
			
			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			//Reuse the view to make the scroll effect smooth
			if(convertView == null)
				convertView = inflater.inflate(R.layout.list_item, parent, false);
			
			// If the ListView needs to display the records of StudentDetails objects
			if(records.get(position).getClass().isInstance(new StudentDetails())){
				final StudentDetails studentDetails = (StudentDetails) records.get(position);
				try {
					// Invoking refresh() method to fetch the reference data stored into TeacherDetails table/object
					// Basically, it is an example of Lazy loading. It will join two tables internally only on demand
					teacherDao.refresh(studentDetails.teacher);
				} catch (Exception e) {
					e.printStackTrace();
				}
				((TextView)convertView.findViewById(R.id.student_name_tv)).setText(studentDetails.studentName);
				((TextView)convertView.findViewById(R.id.teacher_tv)).setText(studentDetails.teacher.teacherName);
			}
			// If the ListView needs to display the records of TeacherDetails objects
			else{
				final TeacherDetails teacherDetails = (TeacherDetails) records.get(position);
				((TextView)convertView.findViewById(R.id.student_name_tv)).setText(teacherDetails.teacherName);
				((TextView)convertView.findViewById(R.id.teacher_tv)).setText(teacherDetails.address);
			}
			return convertView;
		}
	
}

 

13.      AndroidManifest

Open your AndroidManifest.xml and declare the required activities.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.studentdirectory"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".TeacherAddActivity"
            android:label="@string/app_name" />
        <activity
            android:name=".StudentAddActivity"
            android:label="@string/app_name" />
        <activity
            android:name=".ViewStudentRecordActivity"
            android:label="@string/app_name" />
        <activity
            android:name=".ViewTeacherRecordActivity"
            android:label="@string/app_name" />
        <activity
            android:name=".ViewTeacherDetailsActivity"
            android:label="@string/app_name" />
    </application>

</manifest>

Output :

StudentDirectory Screenshot

Source Code

[purchase_link id=”8040″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

Thank you so much. Please give me tutorial. how to get location folder phisical database studentdir.db in android file manager for debugging?

aan junianto

Android ORMLite with SQLite Database Tutorial

Thank you so much. I was stuck when using 2 database entities where I had an error using OpenHelperManager object. Furtunately now I have a working code thanks to your code.

pranish

Android ORMLite with SQLite Database Tutorial

thanks a lot

RAMAZAN CESUR

Android ORMLite with SQLite Database Tutorial

Thanks for the article. I have a question. If I have twenty model classes, do I need to deal with twenty different Dao classes in my app and do I need to make twenty calls to the createTable method?

Bell leaf

Android ORMLite with SQLite Database Tutorial