Reading and Writing to Database Efficiently in Android

2 min read

Dear friends

Now its time for the Next Tutorial in Series. For anyone want to study Part 1 of tutorial where we developed a notification demo can visit

Reading and Writing to Database Efficiently in Android

Basically its android UIThread that is responsible for presenting that stunning application UX to user. those killer animations are also performed on UIThread. and at last but not the least it is the thread that responds to User’s touches on the screen.

So doing anything on the UIThread that demands greater computing time we generally offload work request to a worker thread.
worker thread does the work on behalf of UIThread and post results back to UIThread if needed.

DB operations can be a time consuming task.

When you run sample application attached at bottom you will see DB operation is very fast. and UI is responding very fast. Its because we are only dealing with single record. But what if you have more than 500 records to be inserted. [ Surely this will gonna take few seconds of time ] .

Thats why as good citizen we do DB Operations in Background using Asynctasks. To know more about Asynctasks you can study my another blog

Lets get down to work

package in.relsellglobal.dbwriterandreadersample;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    DBHandler db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         db = new DBHandler(this);

         new DBWriter().execute();

         new DBReader().execute();


    }

    public class DBWriter extends AsyncTask<Void,Void,Void> {

        @Override
        protected Void doInBackground(Void... params) {
            Student student1 = new Student();
            student1.setStudentName("anil");
            student1.setStudentRollNo(1);
            db.addStudentData(student1);

            Student student2 = new Student();
            student2.setStudentName("sunil");
            student2.setStudentRollNo(2);
            db.addStudentData(student2);

            return null;
        }
    }


    public class DBReader extends AsyncTask<Void,Void,Student> {

        @Override
        protected Student doInBackground(Void... params) {
            Student student = db.fetchStudentData(1);
            return student;
        }

        @Override
        protected void onPostExecute(Student student) {
            super.onPostExecute(student);
            Toast.makeText(MainActivity.this,"Student for Roll No 1 is = "+student.getStudentName(),Toast.LENGTH_LONG).show();

        }
    }


}

 

 

the DB Handler

 

 

package in.relsellglobal.dbwriterandreadersample;

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

/**
 * Created by anilkukreti on 13/05/17.
 */

public class DBHandler extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "students.db";
    public static final int DATABASE_VERSION = 1;
    public static final String STUDENT_TABLE = "student";

    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_ROLL_NO = "roll_no";


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

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_STUDENTS_TABLE = "CREATE TABLE " + STUDENT_TABLE + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_ROLL_NO + " TEXT" + ")";
        db.execSQL(CREATE_STUDENTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + STUDENT_TABLE);
        // Create tables again
        onCreate(db);
    }

    public void addStudentData(Student obj) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME,obj.getStudentName());
        values.put(KEY_ROLL_NO,obj.getStudentRollNo());

        // Inserting Row
        db.insert(STUDENT_TABLE, null, values);
        db.close(); // Closing database connection

    }

    public void removeStudentData(Student obj) {

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(STUDENT_TABLE, KEY_ID + " = ?",
                new String[] { String.valueOf(obj.getStudentId()) });
        db.close();

    }

    public int updateStudentData(Student obj) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, obj.getStudentName());
        values.put(KEY_ROLL_NO, obj.getStudentRollNo());

        // updating row
        return db.update(STUDENT_TABLE, values, KEY_ID + " = ?",
                new String[] { String.valueOf(obj.getStudentId()) });

    }

    public Student fetchStudentData(int rollNo) {

        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(STUDENT_TABLE, new String[] { KEY_ID,
                        KEY_NAME, KEY_ROLL_NO }, KEY_ROLL_NO + "=?",
                new String[] { String.valueOf(rollNo) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Student student = new Student();
        student.setStudentId(cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID)));
        student.setStudentName(cursor.getString(cursor.getColumnIndexOrThrow(KEY_NAME)));
        student.setStudentRollNo(cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ROLL_NO)));

        return student;
    }


}

Pojo Class

 

package in.relsellglobal.dbwriterandreadersample;

/**
 * Created by anilkukreti on 13/05/17.
 */

public class Student {
    private int studentId;
    private String studentName;
    private int studentRollNo;

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public int getStudentRollNo() {
        return studentRollNo;
    }

    public void setStudentRollNo(int studentRollNo) {
        this.studentRollNo = studentRollNo;
    }
}

Code DBWriterAndReaderSample

if you have question please post your question in google form

Thanks for reading.