How do I get Room database size

Viewed 1776

I want to monitor the size of my Room database in my android app. I have searched around for a while and found little info about exactly how to do that. Is there any Room (SQLite) command to determine the db size ?

3 Answers

After a while, searching around, I found some "old" (aka ancient) pragma calls which I tested, and it worked somehow. Not in the need to get the exact values, but a hint of the usage.

You could do a @Dao @Query in Room like this:

@Dao
interface SystemDao{
  @Query("""
    SELECT s.*, c.* 
    FROM pragma_page_size as s
    JOIN pragma_page_count as c
  """)
  suspend fun getDatabaseSizeInfo():List<SystemDatabaseSizeInfo>   
}

And in the data class "pojo" you define:

data class SystemDatabaseSizeInfo(
  var page_size:Int?=null,
  var page_count:Int?=null
)

Since the result from the pragma queries are page_size and page_count. Theese can later be multiplied, or presented separately.

You can read about SQLite pragma calls here: https://www.sqlite.org/pragma.html

There are bunch of other pragma queries which may useful, but you should use them visely, since some of them may be devastating for the stability of the SQLite DB.

Android IDE/lint may render theese commands not valid (red), but if you have AS4.1Cx (C6+) you may be able to run some of them in the Database Inspector tool to see if they work. I have filed an issuetracker incident on that here: https://issuetracker.google.com/157374656

Thank you for all who answered, you led me to the correct path with intensive googling...

Haven't tried it, but it should be something alike this:

fun getSize(context: Context, fileName: String) : Long {
    val file = context.getDatabasePath(fileName)
    return file.length()
}

As @Commonsware suggested, unless the write-ahead log had been committed, it may be inaccurate (it's these *.wal files in the same directory). And one can't just add up the sizes, but would have to check if the database file is currently in use and if so, close it first. Another option would be .disableWriteAheadLogging(), which comes at the cost of some performance.

In Android Studio in debug mode in either a device or emulator, you can use the Device File Explorer which is at bottom right of Android Studio, goto data -> data -> your package name (eg. com.myapp) -> databases:

enter image description here

Related