Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.roomproject
- import android.content.ContentProvider
- import android.content.ContentUris
- import android.content.ContentValues
- import android.content.UriMatcher
- import android.database.Cursor
- import android.net.Uri
- import androidx.room.Room
- import com.example.roomproject.database.MusicDao
- import com.example.roomproject.database.MusicDatabase
- class MusicProvider : ContentProvider {
- internal var cursor: Cursor? = null
- internal var musicDao: MusicDao? = null
- init {
- URI_MATCHER.addURI(AUTHORITY, TABLE_ALBUM, ALBUM_TABLE_CODE)
- URI_MATCHER.addURI(AUTHORITY, "$TABLE_ALBUM/*" , ALBUM_ROW_CODE)
- }
- companion object {
- private val TAG = MusicProvider.javaClass.simpleName
- private val AUTHORITY = "com.example.roomproject.musicprovider"
- private val TABLE_ALBUM = "album"
- private val URI_MATCHER = UriMatcher(-1)
- private val ALBUM_TABLE_CODE = 101
- private val ALBUM_ROW_CODE = 102
- }
- constructor() {
- }
- override fun onCreate(): Boolean {
- if (context != null) {
- val musicDao = Room
- .databaseBuilder(context.applicationContext, MusicDatabase::class.java, "music_database")
- .build()
- .getMusicDao()
- return true
- }
- return false
- }
- override fun getType(uri: Uri): String? {
- when (URI_MATCHER.match(uri)) {
- ALBUM_TABLE_CODE -> return "vnd.android.cursor.dir/$AUTHORITY.$TABLE_ALBUM"
- ALBUM_ROW_CODE -> return "vnd.android.cursor.item/$AUTHORITY.$TABLE_ALBUM"
- else -> throw UnsupportedOperationException("not yet implemented")
- }
- }
- override fun query(uri: Uri, projection: Array<String>?, selection: String?,
- selectionArgs: Array<String>?, sortOrder: String?): Cursor? {
- val code = URI_MATCHER.match(uri)
- if (code != ALBUM_ROW_CODE && code != ALBUM_TABLE_CODE) return null
- if (code == ALBUM_TABLE_CODE) {
- cursor = musicDao?.getAlbumsCursor()
- } else {
- cursor = musicDao?.getAlbumsWithIdCursor(ContentUris.parseId(uri).toInt())
- }
- return cursor
- }
- override fun insert(uri: Uri, values: ContentValues?): Uri? {
- throw java.lang.UnsupportedOperationException("not yet implemented")
- }
- override fun update(
- uri: Uri, values: ContentValues?, selection: String?,
- selectionArgs: Array<String>?): Int {
- throw java.lang.UnsupportedOperationException("not yet implemented")
- }
- override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
- throw java.lang.UnsupportedOperationException("not yet implemented")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement