An example of Android StrictMode output (with improper database access)

I was just working with an example of how to use Android’s new Room Persistence Library, and the example I was working with ran some of its code on the main Android thread, also known as its “UI thread.” I knew this was bad, but I wanted to start with someone’s example, and then figure out a good way to get the Room method calls to run on a background thread, such as using an AsyncTask. (The Android docs don’t specify a “best practice” for this atm.)

One way to make sure you don’t accidentally run code like this on the main Android thread is to enable Android’s StrictMode. Per the StrictMode documentation, you can enable StrictMode in the onCreate method of an Activity like this:

protected void onCreate(Bundle savedInstanceState) {

    // detects things you might be doing by accident and brings them to your attention so you can fix them
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
            .detectNetwork()   // or .detectAll() for all detectable problems
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()

After I enabled StrictMode in this example application and ran it again, I saw A LOT of logcat output that looks like this:

07-20 10:19:19.775 18278-18278/ D/StrictMode: StrictMode policy violation; 
~duration=17 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=65543 violation=2
      at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(
      at android.database.sqlite.SQLiteConnection.applyBlockGuardPolicy(
      at android.database.sqlite.SQLiteConnection.executeForLong(
      at android.database.sqlite.SQLiteConnection.setPageSize(
      at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(
      at android.database.sqlite.SQLiteDatabase.openInner(
      at android.database.sqlite.SQLiteDatabase.openDatabase(
      at android.content.ContextWrapper.openOrCreateDatabase(
      at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(
      at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(
      at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(
      at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(
      at$Lambda$0.$m$0(Unknown Source)
      at$Lambda$0.onClick(Unknown Source)
      at android.view.View.performClick(
      at android.view.View$
      at android.os.Handler.handleCallback(
      at android.os.Handler.dispatchMessage(
      at android.os.Looper.loop(
      at java.lang.reflect.Method.invoke(Native Method)

That’s what StrictMode does: it shows you when you have long-running tasks such as database, network, and file I/O methods running on the main thread, which again is a no-no.

In summary, if you wanted to see how to enable StrictMode, and what the StrictMode output looks like, I hope this is helpful.