From 5d9dcd97017fb7dedb47ea3b6b8413fbcda98e03 Mon Sep 17 00:00:00 2001 From: azuo Date: Thu, 23 Sep 2021 00:23:42 +0800 Subject: [PATCH] Replace Realm with Room. --- app/build.gradle | 6 +- .../anotherwidget/AWApplication.kt | 13 +- .../anotherwidget/db/EventRepository.kt | 119 +++++++++++------- .../anotherwidget/models/Event.kt | 39 +++--- .../receivers/UpdatesReceiver.kt | 8 +- .../services/UpdateCalendarService.kt | 2 +- build.gradle | 4 - 7 files changed, 106 insertions(+), 85 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 653062c..1f66680 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -7,8 +7,6 @@ apply plugin: 'com.google.firebase.crashlytics' apply plugin: 'kotlin-android' apply plugin: 'kotlin-kapt' -apply plugin: 'realm-android' - def apikeyPropertiesFile = rootProject.file("apikey.properties") def apikeyProperties = new Properties() apikeyProperties.load(new FileInputStream(apikeyPropertiesFile)) @@ -88,6 +86,10 @@ dependencies { // EventBus implementation 'org.greenrobot:eventbus:3.2.0' + // Room + implementation "androidx.room:room-runtime:2.3.0" + kapt "androidx.room:room-compiler:2.3.0" + // Navigation implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5' implementation 'androidx.navigation:navigation-ui-ktx:2.3.5' diff --git a/app/src/main/java/com/tommasoberlose/anotherwidget/AWApplication.kt b/app/src/main/java/com/tommasoberlose/anotherwidget/AWApplication.kt index 7f5c79b..4d3c3f0 100644 --- a/app/src/main/java/com/tommasoberlose/anotherwidget/AWApplication.kt +++ b/app/src/main/java/com/tommasoberlose/anotherwidget/AWApplication.kt @@ -7,10 +7,6 @@ import androidx.appcompat.app.AppCompatDelegate import com.chibatching.kotpref.Kotpref import com.google.firebase.crashlytics.FirebaseCrashlytics import com.tommasoberlose.anotherwidget.global.Preferences -import com.tommasoberlose.anotherwidget.utils.checkGrantedPermission -import io.realm.Realm -import io.realm.RealmConfiguration -import net.danlew.android.joda.JodaTimeAndroid class AWApplication : Application() { override fun onCreate() { @@ -24,12 +20,5 @@ class AWApplication : Application() { // Dark theme AppCompatDelegate.setDefaultNightMode(Preferences.darkThemePreference) - - // Realm - Realm.init(this) - val config = RealmConfiguration.Builder() - .deleteRealmIfMigrationNeeded() - .build() - Realm.setDefaultConfiguration(config) } -} \ No newline at end of file +} diff --git a/app/src/main/java/com/tommasoberlose/anotherwidget/db/EventRepository.kt b/app/src/main/java/com/tommasoberlose/anotherwidget/db/EventRepository.kt index 7d32eb5..f9d1935 100644 --- a/app/src/main/java/com/tommasoberlose/anotherwidget/db/EventRepository.kt +++ b/app/src/main/java/com/tommasoberlose/anotherwidget/db/EventRepository.kt @@ -3,32 +3,37 @@ package com.tommasoberlose.anotherwidget.db import android.content.Context import android.provider.CalendarContract import android.util.Log +import androidx.room.Dao +import androidx.room.Database +import androidx.room.Insert +import androidx.room.Query +import androidx.room.Room +import androidx.room.RoomDatabase import com.chibatching.kotpref.bulk import com.tommasoberlose.anotherwidget.global.Preferences import com.tommasoberlose.anotherwidget.helpers.CalendarHelper.applyFilters +import com.tommasoberlose.anotherwidget.helpers.CalendarHelper.sortEvents import com.tommasoberlose.anotherwidget.models.Event import com.tommasoberlose.anotherwidget.receivers.UpdatesReceiver import com.tommasoberlose.anotherwidget.ui.widgets.MainWidget -import io.realm.Realm -import io.realm.RealmResults import java.util.* import kotlin.Comparator import kotlin.collections.ArrayList class EventRepository(val context: Context) { - private val realm by lazy { Realm.getDefaultInstance() } + private val db by lazy { EventDatabase.getDatabase(context) } fun saveEvents(eventList: List) { - realm.executeTransaction { realm -> - realm.where(Event::class.java).findAll().deleteAllFromRealm() - realm.copyToRealm(eventList) + db.runInTransaction{ + db.dao().run { + deleteAll() + insertAll(eventList) + } } } fun clearEvents() { - realm.executeTransaction { realm -> - realm.where(Event::class.java).findAll().deleteAllFromRealm() - } + db.dao().deleteAll() } fun resetNextEventData() { @@ -44,11 +49,11 @@ class EventRepository(val context: Context) { } fun saveNextEventData(event: Event) { - Preferences.nextEventId = event.eventID + Preferences.nextEventId = event.id } fun getNextEvent(): Event? { - val nextEvent = getEventByEventId(Preferences.nextEventId) + val nextEvent = getEventById(Preferences.nextEventId) val now = Calendar.getInstance().timeInMillis val limit = Calendar.getInstance().apply { timeInMillis = now @@ -64,43 +69,33 @@ class EventRepository(val context: Context) { else -> add(Calendar.HOUR, 6) } } - val event = if (nextEvent != null && nextEvent.endDate > now && nextEvent.startDate <= limit.timeInMillis) { + return if (nextEvent != null && nextEvent.endDate > now && nextEvent.startDate <= limit.timeInMillis) { nextEvent } else { val events = getEvents() if (events.isNotEmpty()) { val newNextEvent = events.first() - Preferences.nextEventId = newNextEvent.eventID + Preferences.nextEventId = newNextEvent.id newNextEvent } else { resetNextEventData() null } } - return try { - realm.copyFromRealm(event!!) - } catch (ex: Exception) { - event - } } - fun getEventByEventId(id: Long): Event? { - val event = realm.where(Event::class.java).equalTo("eventID", id).findFirst() - return try { - realm.copyFromRealm(event!!) - } catch (ex: Exception) { - event - } + fun getEventById(id: Long): Event? { + return db.dao().findById(id) } fun goToNextEvent() { val eventList = getEvents() if (eventList.isNotEmpty()) { - val index = eventList.indexOfFirst { it.eventID == Preferences.nextEventId } + val index = eventList.indexOfFirst { it.id == Preferences.nextEventId } if (index > -1 && index < eventList.size - 1) { - Preferences.nextEventId = eventList[index + 1].eventID + Preferences.nextEventId = eventList[index + 1].id } else { - Preferences.nextEventId = eventList.first().eventID + Preferences.nextEventId = eventList.first().id } } else { resetNextEventData() @@ -114,11 +109,11 @@ class EventRepository(val context: Context) { fun goToPreviousEvent() { val eventList = getEvents() if (eventList.isNotEmpty()) { - val index = eventList.indexOfFirst { it.eventID == Preferences.nextEventId } + val index = eventList.indexOfFirst { it.id == Preferences.nextEventId } if (index > 0) { - Preferences.nextEventId = eventList[index - 1].eventID + Preferences.nextEventId = eventList[index - 1].id } else { - Preferences.nextEventId = eventList.last().eventID + Preferences.nextEventId = eventList.last().id } } else { resetNextEventData() @@ -130,13 +125,7 @@ class EventRepository(val context: Context) { } fun getFutureEvents(): List { - val now = Calendar.getInstance().timeInMillis - realm.refresh() - return realm - .where(Event::class.java) - .greaterThan("endDate", now) - .findAll() - .applyFilters() + return db.dao().findFuture(Calendar.getInstance().timeInMillis).applyFilters().sortEvents() } private fun getEvents(): List { @@ -155,18 +144,54 @@ class EventRepository(val context: Context) { else -> add(Calendar.HOUR, 6) } } - realm.refresh() - return realm - .where(Event::class.java) - .greaterThan("endDate", now) - .lessThanOrEqualTo("startDate", limit.timeInMillis) - .findAll() - .applyFilters() + return db.dao().find(now, limit.timeInMillis).applyFilters().sortEvents() } fun getEventsCount(): Int = getEvents().size fun close() { - realm.close() + // db.close() } -} \ No newline at end of file + + @Dao + interface EventDao { + @Query("SELECT * FROM events WHERE id = :id LIMIT 1") + fun findById(id: Long) : Event? + + @Query("SELECT * FROM events WHERE end_date > :from") + fun findFuture(from: Long) : List + + @Query("SELECT * FROM events WHERE end_date > :from and start_date <= :to") + fun find(from: Long, to: Long) : List + + @Insert + fun insertAll(events: List) + + @Query("DELETE FROM events") + fun deleteAll() + } + + @Database(entities = arrayOf(Event::class), version = 1, exportSchema = false) + abstract class EventDatabase : RoomDatabase() { + abstract fun dao(): EventDao + + companion object { + private var INSTANCE: EventDatabase? = null + + fun getDatabase(context: Context): EventDatabase { + // if the INSTANCE is not null, then return it, + // if it is, then create the database + return INSTANCE ?: synchronized(this) { + val instance = Room.databaseBuilder( + context.applicationContext, + EventDatabase::class.java, + "events" + ).allowMainThreadQueries().build() + INSTANCE = instance + // return instance + instance + } + } + } + } +} diff --git a/app/src/main/java/com/tommasoberlose/anotherwidget/models/Event.kt b/app/src/main/java/com/tommasoberlose/anotherwidget/models/Event.kt index 34575d9..70d7ad7 100644 --- a/app/src/main/java/com/tommasoberlose/anotherwidget/models/Event.kt +++ b/app/src/main/java/com/tommasoberlose/anotherwidget/models/Event.kt @@ -1,26 +1,35 @@ package com.tommasoberlose.anotherwidget.models import android.provider.CalendarContract -import io.realm.RealmObject -import java.util.Date +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey /** * Created by tommaso on 05/10/17. */ -open class Event( - var id: Long = 0, - var eventID: Long = 0, - var title: String = "", - var startDate: Long = 0, - var endDate: Long = 0, - var calendarID: Int = 0, - var allDay: Boolean = false, - var address: String = "", - var selfAttendeeStatus: Int = CalendarContract.Attendees.ATTENDEE_STATUS_NONE, - var availability: Int = CalendarContract.EventsEntity.AVAILABILITY_BUSY -) : RealmObject() { +@Entity(tableName = "events") +data class Event( + @PrimaryKey + val id: Long = 0, + @ColumnInfo(name = "event_id") + val eventID: Long = 0, + val title: String = "", + @ColumnInfo(name = "start_date") + val startDate: Long = 0, + @ColumnInfo(name = "end_date") + val endDate: Long = 0, + @ColumnInfo(name = "calendar_id") + val calendarID: Long = 0, + @ColumnInfo(name = "all_day") + val allDay: Boolean = false, + val address: String = "", + @ColumnInfo(name = "self_attendee_status") + val selfAttendeeStatus: Int = CalendarContract.Attendees.ATTENDEE_STATUS_NONE, + val availability: Int = CalendarContract.EventsEntity.AVAILABILITY_BUSY +)/* { override fun toString(): String { return "Event:\nEVENT ID: " + eventID + "\nTITLE: " + title + "\nSTART DATE: " + Date(startDate) + "\nEND DATE: " + Date(endDate) + "\nCAL ID: " + calendarID + "\nADDRESS: " + address } -} +}*/ diff --git a/app/src/main/java/com/tommasoberlose/anotherwidget/receivers/UpdatesReceiver.kt b/app/src/main/java/com/tommasoberlose/anotherwidget/receivers/UpdatesReceiver.kt index 2997b1b..afc612c 100644 --- a/app/src/main/java/com/tommasoberlose/anotherwidget/receivers/UpdatesReceiver.kt +++ b/app/src/main/java/com/tommasoberlose/anotherwidget/receivers/UpdatesReceiver.kt @@ -95,7 +95,7 @@ class UpdatesReceiver : BroadcastReceiver() { setEventUpdate(context, event) } } else { - val event = eventRepository.getEventByEventId(eventId) + val event = eventRepository.getEventById(eventId) if (event != null) { setEventUpdate(context, event) } @@ -166,11 +166,11 @@ class UpdatesReceiver : BroadcastReceiver() { fireTime.coerceAtLeast(now.timeInMillis + 1000 * 60), PendingIntent.getBroadcast( context, - event.eventID.toInt(), + event.id.toInt(), Intent(context, UpdatesReceiver::class.java).apply { action = Actions.ACTION_TIME_UPDATE if (event.startDate > now.timeInMillis) - putExtra(EVENT_ID, event.eventID) + putExtra(EVENT_ID, event.id) }, PendingIntent.FLAG_UPDATE_CURRENT ) @@ -185,7 +185,7 @@ class UpdatesReceiver : BroadcastReceiver() { }, 0)) val eventRepository = EventRepository(context) eventRepository.getFutureEvents().forEach { - cancel(PendingIntent.getBroadcast(context, it.eventID.toInt(), Intent(context, UpdatesReceiver::class.java).apply { + cancel(PendingIntent.getBroadcast(context, it.id.toInt(), Intent(context, UpdatesReceiver::class.java).apply { action = Actions.ACTION_TIME_UPDATE }, 0)) } diff --git a/app/src/main/java/com/tommasoberlose/anotherwidget/services/UpdateCalendarService.kt b/app/src/main/java/com/tommasoberlose/anotherwidget/services/UpdateCalendarService.kt index cef9fe0..be45806 100644 --- a/app/src/main/java/com/tommasoberlose/anotherwidget/services/UpdateCalendarService.kt +++ b/app/src/main/java/com/tommasoberlose/anotherwidget/services/UpdateCalendarService.kt @@ -143,7 +143,7 @@ class UpdateCalendarService : Service() { title = e.title ?: "", startDate = instance.begin, endDate = instance.end, - calendarID = e.calendarId.toInt(), + calendarID = e.calendarId, allDay = e.allDay, address = e.eventLocation ?: "", selfAttendeeStatus = e.selfAttendeeStatus.toInt(), diff --git a/build.gradle b/build.gradle index bee755d..09745b4 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,6 @@ buildscript { jcenter() maven { url 'https://jitpack.io' } mavenCentral() - } dependencies { classpath 'com.android.tools.build:gradle:4.2.0' @@ -17,8 +16,6 @@ buildscript { // Add the Crashlytics Gradle plugin. classpath 'com.google.firebase:firebase-crashlytics-gradle:2.5.2' - classpath 'io.realm:realm-gradle-plugin:10.4.0' - // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } @@ -30,7 +27,6 @@ allprojects { jcenter() maven { url 'https://jitpack.io' } mavenCentral() - } }