forked from kimtaesu/FlickrAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FlickrDatabase.kt
64 lines (55 loc) · 1.75 KB
/
FlickrDatabase.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.hucet.flickr.db
import android.content.Context
import androidx.annotation.VisibleForTesting
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.hucet.flickr.db.dao.FlickrDao
import com.hucet.flickr.vo.Photo
import com.hucet.flickr.vo.PhotoSearchResult
@Database(
entities = [
Photo::class,
PhotoSearchResult::class
],
version = 1,
exportSchema = false
)
abstract class FlickrDatabase : RoomDatabase() {
abstract fun flickrDao(): FlickrDao
companion object {
private var INSTANCE: FlickrDatabase? = null
@Synchronized
fun getInstance(context: Context): FlickrDatabase {
if (INSTANCE == null) {
INSTANCE = buildDatabase(context)
}
return INSTANCE!!
}
@VisibleForTesting
@Synchronized
fun getInstanceInMemory(context: Context): FlickrDatabase {
INSTANCE = Room.inMemoryDatabaseBuilder(context.applicationContext, FlickrDatabase::class.java)
.allowMainThreadQueries()
.populate()
.build()
return INSTANCE!!
}
private fun buildDatabase(context: Context): FlickrDatabase {
return Room.databaseBuilder(
context,
FlickrDatabase::class.java, "flickr13"
)
.populate()
.build()
}
}
}
private fun <T : RoomDatabase> RoomDatabase.Builder<T>.populate(): RoomDatabase.Builder<T> {
return this.addCallback(object : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
}
})
}