Insert and retrieve data using Android ORMLite database | Object Relational Mapping Lite (ORM Lite) gives some lightweight functionality to store and retrieve Java Objects to SQL databases while avoiding the complexity. It supports a number of SQL databases like MySQL, Postgres, Microsoft SQL Server, H2, Derby, HSQLDB, and SQLite.

Some features of OrmLite are

  • It is easy to setup a class by simply adding Java annotations.
  • It provides DAO (Powerful abstract Database Access Object) classes.
  • It provides Auto generates SQL to create.
  • It provides Flexible QueryBuilder so that easily construct simple and complex queries.
  • It can be used for complicated database operation.

In this tutorial, we will learn how to use ORMLite for CRUD (Create, Read, Update, Delete) operations.

Download Project – Here

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Creating New Project -> ORMLiteDemo

Open your Android Studio & create a new Project, have taken Blank Activity for this project and clicked finish.

Add the dependencies

Open your app-level dependencies file and add the following code.

compile 'com.j256.ormlite:ormlite-android:4.48'

Creating Layout -> activity_main.xml

Creating activity_main.xml file inside Layout folder which contains two buttons, one button is add information and the second button is show information.The first button is for add information to the database and the second button is for retrieve data from database and show.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:padding="10dp"
    >

    <Button
        android:id="@+id/addInformation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:text="Add Information" />

    <Button
        android:id="@+id/showInformation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/addInformation"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="103dp"
        android:text="Show Information" />
</RelativeLayout>

 Creating -> MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button addInformation,showInformation;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addInformation = (Button)findViewById(R.id.addInformation);
        showInformation = (Button)findViewById(R.id.showInformation);
        addInformation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, InsertDataActivity.class));
            }
        });
        showInformation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, DisplayDataActivity.class));
            }
        });
    }
}

We will provide our Activity with the view of activity_maps by writing

setContentView(R.layout.activity_main);

We are created onClickListener for both buttons.When user will click buttons it will open respective activity.

Creating a class for database table -> Information_Model

This class is configured to be determined on to a database by using ORMLite annotations. The @DatabaseField annotations created the fields on the database columns with the columnName id and name.We have created an auto generated integer type primary key named as id.

import com.j256.ormlite.field.DatabaseField;
public class Information_Model {

    @DatabaseField(generatedId = true, columnName = "id")
    public int id;
    @DatabaseField(columnName = "name")
    public String name;
    public String email;
    public Information_Model(){
    }
    public Information_Model(final String name, final String email){
        this.name = name;
        this.email = email;
    }
}

Create an SQLite database helper class -> Database_Helper

This class is extended from OrmLiteSqliteOpenHelper.We have to override two methods, onCreate() and onUpgrade() .onCreate() method includes the table creation statements and other first-time configuration logics and onUpgrade() method is used for any update in the database.

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

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;

public class Database_Helper extends OrmLiteSqliteOpenHelper {
    private static final String DB_NAME = "information.db";
    private static final int DB_VERSION = 1;
    private Dao<Information_Model, Integer> informationDao;
    public Database_Helper(Context context) {
        super(context,DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
                TableUtils.createTable(connectionSource, Information_Model.class);
            } catch (java.sql.SQLException e) {
                e.printStackTrace();
            }
        }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource,
 int oldVersion, int newVersion) {

            try {
                TableUtils.dropTable(connectionSource, Information_Model.class, true);
            } catch (java.sql.SQLException e) {
                e.printStackTrace();
            }
            onCreate(database, connectionSource);
    }
    public Dao<Information_Model, Integer> getInformationDao() throws SQLException, 
java.sql.SQLException {
        if (informationDao == null) {
            informationDao = getDao(Information_Model.class);
        }
        return informationDao;
    }
}

In this class we have created DAO method, it is a most important keyword in ORMLite to handle the database.Create, delete, read, and the update will be done through DAOs.

public Dao<Information_Model, Integer> getInformationDao() throws SQLException, 
java.sql.SQLException {
        if (informationDao == null) {
            informationDao = getDao(Information_Model.class);
        }
        return informationDao;
    }

 Creating >InsertDataActivity.java

We can interact with SQLite database only through the DAOs which are the part of Datatabase_Helper class, so at first, we are taking a reference to that class.Then we create an object of Information_Model for insert data to the database.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

public class InsertDataActivity extends AppCompatActivity {
    private Database_Helper database_helper = null;
    private EditText addName,addEmail;
    private Button addBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert_data);
        addName = (EditText)findViewById(R.id.addName);
        addEmail = (EditText)findViewById(R.id.addEmail);
        addBtn = (Button)findViewById(R.id.addBtn);

        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(addName.getText().toString().trim().length() > 0 &&
                        addEmail.getText().toString().trim().length() > 0){
                    final Information_Model information_model = new Information_Model();
                    information_model.name = addName.getText().toString();
                    information_model.email = addEmail.getText().toString();

                    try {
                        final Dao<Information_Model, Integer> informationDao = 
                              getHelper().getInformationDao();
                        informationDao.create(information_model);
                        reset();
                    } catch (java.sql.SQLException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
    }
    private void reset()
    {
        addName.setText("");
        addEmail.setText("");
    }
    private Database_Helper getHelper() {
        if (database_helper == null) {
            database_helper = OpenHelperManager.getHelper(this,Database_Helper.class);
        }
        return database_helper;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (database_helper != null) {
            OpenHelperManager.releaseHelper();
            database_helper = null;
        }
    }
}

We initialize Database_Helper for future use.

private Database_Helper getHelper() {
        if (database_helper == null) {
            database_helper = OpenHelperManager.getHelper(this,Database_Helper.class);
        }
        return database_helper;
    }

Creating Layout -> activity_insert_data.xml

This layout file contains two edittexts named name and email and an Add Information button.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    >


    <EditText
        android:id="@+id/addName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="24dp"
        android:ems="10"
        android:hint="Enter your Name"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/addEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/addName"
        android:layout_marginTop="15dp"
        android:ems="10"
        android:hint="Enter your Email"
        android:inputType="textEmailAddress" />

    <Button
        android:id="@+id/addBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/addEmail"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="74dp"
        android:text="Add Information" />
</RelativeLayout>

Creating Layout -> activity_display_data.xml

To display the data we create this layout file, which contains a listview.

<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:padding="10dp" >

    <TextView
        android:id="@+id/details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:text="View Details"
        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>

Creating Layout -> list_view.xml

This XML file is created for display the stored data as a table from.

<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="#000000" >

        <TextView
            android:id="@+id/name"
            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="Name "
            android:textSize="15sp" />

        <TextView
            android:id="@+id/email"
            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="Email "
            android:textSize="15sp" />
    </TableRow>

</LinearLayout>

Creating an array adapter ->InformationArrayAdapter.java

We have created a class InformationArrayAdapter. This is an array adapter class for listview.We are declared DAO to communicate the table which is created in the database.At last, we display our data via listview.

Related:

Android Realm database in Android(Insert & retrieve data from database)

How to insert the data into SQLite database in Android

Store data using SQLite by fetching from ContentProvider and display using RecyclerView

Display data in Recyclerview using SQLiteCursor Class in android

SQLite database tutorial

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.j256.ormlite.dao.Dao;

import java.util.List;
class InformationArrayAdapter extends ArrayAdapter<String> {
    private LayoutInflater layoutInflater;
    private List list;
    private Dao<Information_Model,Integer>information_Dao;
    public InformationArrayAdapter(Context context, int resource, List objects, 
         Dao<Information_Model, Integer> information_Dao) {
        super(context, resource, objects);
        this.list = objects;
        this.information_Dao = information_Dao;
        layoutInflater = (LayoutInflater) context.getSystemService
         (Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null)
            convertView = layoutInflater.inflate(R.layout.list_view, parent, false);
        if (list.get(position).getClass().isInstance(new Information_Model())){
            final Information_Model information_model = (Information_Model)list.get(position);
           ((TextView)convertView.findViewById(R.id.name)).setText(information_model.name);
            ((TextView)convertView.findViewById(R.id.email)).setText(information_model.email);
        }
        return convertView;
    }
}

we have created getView method.To make scrollview smooth we used

if(convertView == null)
            convertView = layoutInflater.inflate(R.layout.list_view, parent, false);

For display the data in listview

if (list.get(position).getClass().isInstance(new Information_Model())){
            final Information_Model information_model = (Information_Model)list.get(position);
           ((TextView)convertView.findViewById(R.id.name)).setText(information_model.name);
            ((TextView)convertView.findViewById(R.id.email)).setText(information_model.email);
        }

Creating ->DisplayDataActivity

We have added delete feature.When user long press on a list view it will delete data from the database.

import android.content.Context;
import android.content.DialogInterface;
import android.database.SQLException;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

import java.util.List;

public class DisplayDataActivity extends AppCompatActivity 
implements AdapterView.OnItemLongClickListener {
    private Database_Helper database_helper = null;
    private ListView listView;
    private int selectPosition = -1;
    private Dao<Information_Model, Integer> informationDao;
    private List<Information_Model> informationList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_data);
        listView = (ListView)findViewById(R.id.listview);

        try {
            informationDao =getHelper().getInformationDao();
            informationList = informationDao.queryForAll();
            final LayoutInflater layoutInflater = (LayoutInflater)this.
            getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View view = layoutInflater.inflate(R.layout.list_view,listView,false);
            listView.setAdapter(new InformationArrayAdapter(this,R.layout.
             list_view,informationList,informationDao));
            listView.addHeaderView(view);
            listView.setOnItemLongClickListener(this);
        } catch (java.sql.SQLException e) {
            e.printStackTrace();
        }

    }
    private Database_Helper getHelper() {
        if (database_helper == null) {
            database_helper = OpenHelperManager.getHelper(this, Database_Helper.class);
        }
        return database_helper;
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if(position > 0)
        {
            selectPosition = position - 1;
            showDialog();
        }
        return false;
    }

    private void showDialog() {
        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Do you want to delete?");
        alertDialogBuilder.setTitle("Delete");
        alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    informationDao.delete(informationList.get(selectPosition));
                    informationList.remove(selectPosition);
                    listView.invalidateViews();
                    selectPosition = -1;
                } catch (java.sql.SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        final AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (database_helper != null) {
            OpenHelperManager.releaseHelper();
            database_helper = null;
        }
    }
}

At first, we take a reference to database helper class,

private Database_Helper database_helper = null;

we initialize the select row position which row user select.

 private int selectPosition = -1;

Then we have created a query to show all the data from the database.

informationList = informationDao.queryForAll();

Set the header of listview

final LayoutInflater layoutInflater = (LayoutInflater)this.
            getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View view = layoutInflater.inflate(R.layout.list_view,listView,false);
            listView.setAdapter(new InformationArrayAdapter(this,R.layout.
             list_view,informationList,informationDao));
            listView.addHeaderView(view);

And links between array adapter and listview.

listView.setAdapter(new InformationArrayAdapter(this,R.layout.
             list_view,informationList,informationDao));

When User will long press on a view it will pop up an alert dialog.We have created showDialog method.We have created a positive button and a negative button. When user will click the Ok button it will remove data from this position of the database.

private void showDialog() {
        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Do you want to delete?");
        alertDialogBuilder.setTitle("Delete");
        alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    informationDao.delete(informationList.get(selectPosition));
                    informationList.remove(selectPosition);
                    listView.invalidateViews();
                    selectPosition = -1;
                } catch (java.sql.SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        final AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

Conclusion
In this Project, you saw how to use Android ORMLite.I hope you will understand the method. In the case of any queries, you may ask questions. Keep following more amazing Android Blogs. If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Related Posts