2

I read many posts telling long operations (like reading DB) should not be excuted on the main Thread.

So far I used CursorLoader (for "reading" ContentResolver) andAsynkTaskLoader(for "reading" my own SQLite DB).

I know to perform Insert, Delete and Update "on" ContentResolver I can use AsyncQueryHandler.

My question is: what's the best way to execute Insert, Delete and Update on my own SQLite db??

Should I simply execute those operations inside the method loadInBackground() of AsyncTaskLoader?

Thank you

MDP
  • 4,177
  • 21
  • 63
  • 119
  • 1
    Use `AsyncTask` and execute updates in `doInBackground` method. But, if your updates light and fast you can freely execute them in the UI thread and make your life a bit easier. – Dusan Aug 25 '17 at 12:33
  • 1
    Thank you man :) – MDP Aug 25 '17 at 12:39
  • 1
    Even slow devices are capable of performing couple of hundreds of simple db operations per second, so there is no point to do single or few operations in the background. https://stackoverflow.com/questions/28188164/android-sqlite-performance – Dusan Aug 25 '17 at 12:39

2 Answers2

1

If your queries are simple and it won't make much time to execute then simply you can use it in main thread itself.

If you're doing big data process then you have two options.

  1. AsyncTask:

If you want to update your UI after an operation, you can use AsyncTask to do the process in a background thread and pass the result into the main thread. for more info about AsyncTaksk click here.

2.Thread

If there is no purpose of updating UI after the operation you can simply use Thread to do it.

Bhuvanesh BS
  • 13,474
  • 12
  • 40
  • 66
1

You can use background handler thread for your purpose.

private Handler mHandler = null;  // global variable
private HandlerThread mHandlerThread = null; // global variable

// Create instance inside onCreate() or another place inside your code so it would be called one's. Also you can make it singleton if required but it's not the right way.

    mHandlerThread = new HandlerThread("HandlerThread");
    mHandlerThread.start();
    mHandler = new Handler(mHandlerThread.getLooper());

// perform background operation like :

handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                       // Do background work here.

                   }
                }, 2000);
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147