KaliMa KaliMa - 7 months ago 9
Java Question

How to correctly perform SQL queries in background thread?

I have a

ViewPager
that has one of the pages containing a
List
which is populated from the SQLite database. This
List
is filled by first grabbing a
Cursor
and then extracting all the various fields into objects that I then add to the
List
.

However I have also read that I should be performing SQL operations in another thread as to not make the entire app lag.

What is the correct way to do this? My SQLite class is implemented as a singleton so it suffices to call
MyDatabaseClass.getInstance(context)
when I need access.

Answer

SQL background queries should be handled like any other background action. You can use e.g. Threads or AsyncTasks to perform them.


Thread example

public void performActionAsync(){
    new Thread(new Runnable(){
        @Override
        public void run(){
           performAction();
        }
    }).start();
}

private void performAction(){
    //perform actions as normal
}
Comments