Skip to content

Commit

Permalink
feat: 教程新增学习记录
Browse files Browse the repository at this point in the history
  • Loading branch information
goweii committed Mar 27, 2022
1 parent 4d813a9 commit 5b116af
Show file tree
Hide file tree
Showing 22 changed files with 468 additions and 97 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# 更新日志

## 2.2.1(74)

- 【新增】教程新增学习记录

## 2.2.0(73)

- 【新增】二楼修改为书籍教程
Expand Down
26 changes: 11 additions & 15 deletions app/src/main/java/per/goweii/wanandroid/db/WanDb.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package per.goweii.wanandroid.db

import android.annotation.SuppressLint
import android.content.Context
import androidx.room.Room
import per.goweii.wanandroid.db.migration.Migration_1_2

/**
* @author CuiZhen
* @date 2020/3/21
*/
@SuppressLint("StaticFieldLeak")
object WanDb {
private var context: Context? = null
private lateinit var context: Context
private var database: WanRoom? = null

@JvmStatic
Expand All @@ -17,22 +20,15 @@ object WanDb {
}

@JvmStatic
private fun db(dbName: String): WanRoom {
database?.run {
if (isOpen) {
if (openHelper.databaseName == dbName) {
return this
} else {
close()
}
}
fun db(): WanRoom {
if (database?.isOpen == true) {
return database!!
}
database = Room.databaseBuilder(context!!, WanRoom::class.java, dbName).build()
database = Room
.databaseBuilder(context, WanRoom::class.java, WanRoom.NAME)
.addMigrations(Migration_1_2())
.build()
return database!!
}

@JvmStatic
fun db(): WanRoom {
return db("wan_db")
}
}
9 changes: 7 additions & 2 deletions app/src/main/java/per/goweii/wanandroid/db/WanRoom.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,15 @@ import per.goweii.wanandroid.db.model.ReadRecordModel
ReadLaterModel::class,
ReadRecordModel::class
],
version = 1,
exportSchema = false
version = WanRoom.VERSION,
exportSchema = false,
)
abstract class WanRoom : RoomDatabase() {
companion object {
const val NAME = "wan_db"
const val VERSION = 2
}

abstract fun readLaterDao(): ReadLaterDao
abstract fun readRecordDao(): ReadRecordDao
}
19 changes: 14 additions & 5 deletions app/src/main/java/per/goweii/wanandroid/db/dao/ReadRecordDao.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package per.goweii.wanandroid.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.*
import per.goweii.wanandroid.db.model.ReadRecordModel

/**
Expand All @@ -12,9 +9,18 @@ import per.goweii.wanandroid.db.model.ReadRecordModel
*/
@Dao
interface ReadRecordDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
@Insert(onConflict = OnConflictStrategy.ABORT)
suspend fun insert(vararg mode: ReadRecordModel)

@Update(onConflict = OnConflictStrategy.ABORT)
suspend fun update(vararg mode: ReadRecordModel)

@Query("UPDATE ReadRecordModel SET lastTime = :lastTime, percent = :percent WHERE (link = :link AND percent < :percent)")
suspend fun updatePercent(link: String, percent: Int, lastTime: Long)

@Query("SELECT * FROM ReadRecordModel WHERE link = :link")
suspend fun findByLink(link: String): ReadRecordModel?

@Query("DELETE FROM ReadRecordModel WHERE link = :link")
suspend fun delete(link: String)

Expand All @@ -24,6 +30,9 @@ interface ReadRecordDao {
@Query("SELECT * FROM ReadRecordModel ORDER BY time DESC LIMIT (:offset), (:count)")
suspend fun findAll(offset: Int, count: Int): List<ReadRecordModel>

@Query("SELECT * FROM ReadRecordModel WHERE link in (:links)")
suspend fun findByLinks(links: List<String>): List<ReadRecordModel>

@Query("""DELETE FROM ReadRecordModel WHERE link NOT IN
(SELECT link FROM ReadRecordModel ORDER BY time DESC LIMIT 0, :maxCount)""")
suspend fun deleteIfMaxCount(maxCount: Int)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package per.goweii.wanandroid.db.executor

import androidx.room.withTransaction
import per.goweii.basic.utils.listener.SimpleCallback
import per.goweii.basic.utils.listener.SimpleListener
import per.goweii.wanandroid.common.Config
Expand All @@ -12,18 +13,64 @@ import per.goweii.wanandroid.db.model.ReadRecordModel
*/
class ReadRecordExecutor : DbExecutor() {

fun add(link: String, title: String, success: SimpleListener, error: SimpleListener) {
fun findByLinks(
link: List<String>,
success: SimpleCallback<List<ReadRecordModel>>,
error: SimpleCallback<Throwable>
) {
execute({
db().readRecordDao().findByLinks(link)
}, {
success.onResult(it)
}, {
error.onResult(it)
})
}

fun add(
link: String,
title: String,
percent: Float,
success: SimpleCallback<ReadRecordModel>,
error: SimpleListener
) {
val time = System.currentTimeMillis()
val model = ReadRecordModel(
link, title, time, time,
(percent * ReadRecordModel.MAX_PERCENT).toInt()
)
execute({
val model = ReadRecordModel(link, title, System.currentTimeMillis())
db().readRecordDao().insert(model)
}, {
success.onResult()
success.onResult(model)
removeIfMaxCount {}
}, {
error.onResult()
})
}

fun updatePercent(
link: String,
percent: Float,
lastTime: Long,
success: SimpleCallback<ReadRecordModel>,
error: SimpleListener
) {
val p = (percent.coerceIn(0f, 1f) * ReadRecordModel.MAX_PERCENT).toInt()
execute({
val db = db()
db.withTransaction {
val dao = db.readRecordDao()
dao.updatePercent(link, p, lastTime)
dao.findByLink(link)!!
}
}, {
success.onResult(it)
}, {
error.onResult()
})
}

fun remove(link: String, success: SimpleListener, error: SimpleListener) {
execute({
db().readRecordDao().delete(link)
Expand All @@ -44,7 +91,12 @@ class ReadRecordExecutor : DbExecutor() {
})
}

fun getList(from: Int, count: Int, success: SimpleCallback<List<ReadRecordModel>>, error: SimpleListener) {
fun getList(
from: Int,
count: Int,
success: SimpleCallback<List<ReadRecordModel>>,
error: SimpleListener
) {
execute({
db().readRecordDao().findAll(from, count)
}, {
Expand Down
21 changes: 21 additions & 0 deletions app/src/main/java/per/goweii/wanandroid/db/migration/Migrations.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
@file:Suppress("ClassName")

package per.goweii.wanandroid.db.migration

import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

class Migration_1_2 : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.beginTransaction()
try {
database.execSQL("ALTER TABLE ReadRecordModel ADD COLUMN percent INTEGER NOT NULL DEFAULT 0")
database.execSQL("ALTER TABLE ReadRecordModel ADD COLUMN lastTime INTEGER NOT NULL DEFAULT 0")
database.setTransactionSuccessful()
} catch (e: Throwable) {
e.printStackTrace()
} finally {
database.endTransaction()
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package per.goweii.wanandroid.db.model

import androidx.annotation.FloatRange
import androidx.annotation.IntRange
import androidx.room.Entity

/**
Expand All @@ -8,7 +10,18 @@ import androidx.room.Entity
*/
@Entity(primaryKeys = ["link"])
data class ReadRecordModel(
val link: String,
val title: String,
val time: Long
)
val link: String,
val title: String,
val time: Long,
val lastTime: Long,
@IntRange(from = 0, to = 10000) val percent: Int,
) {
companion object {
const val MIN_PERCENT = 0
const val MAX_PERCENT = 10000
}

val percentFloat: Float
@FloatRange(from = 0.0, to = 1.0)
get() = (percent.toFloat() / MAX_PERCENT.toFloat()).coerceIn(0f, 1f)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package per.goweii.wanandroid.event;

import io.reactivex.annotations.NonNull;
import per.goweii.wanandroid.db.model.ReadRecordModel;

/**
* @author CuiZhen
* @date 2019/5/17
* GitHub: https://github.com/goweii
*/
public class ReadRecordAddedEvent extends BaseEvent {
private final ReadRecordModel readRecordModel;

public ReadRecordAddedEvent(@NonNull ReadRecordModel readRecordModel) {
this.readRecordModel = readRecordModel;
}

@NonNull
public ReadRecordModel getReadRecordModel() {
return readRecordModel;
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package per.goweii.wanandroid.event;

import io.reactivex.annotations.NonNull;

public class ReadRecordUpdateEvent extends BaseEvent {
private final String mLink;
private String mTitle;
private Long mTime;
private Float mPercent;

public ReadRecordUpdateEvent(@NonNull String link) {
this.mLink = link;
}

public String getLink() {
return mLink;
}

public String getTitle() {
return mTitle;
}

public void setTitle(String title) {
this.mTitle = title;
}

public Long getTime() {
return mTime;
}

public void setTime(Long time) {
this.mTime = time;
}

public Float getPercent() {
return mPercent;
}

public void setPercent(Float percent) {
this.mPercent = percent;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@ import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import kotlinx.android.synthetic.main.activity_book_intro.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import per.goweii.basic.core.base.BaseActivity
import per.goweii.basic.utils.ResUtils
import per.goweii.wanandroid.R
import per.goweii.wanandroid.event.ReadRecordAddedEvent
import per.goweii.wanandroid.event.ReadRecordUpdateEvent
import per.goweii.wanandroid.module.book.adapter.BookChapterAdapter
import per.goweii.wanandroid.module.book.bean.BookIntroBean
import per.goweii.wanandroid.module.book.contract.BookIntroPresenter
Expand Down Expand Up @@ -76,6 +80,36 @@ class BookIntroActivity : BaseActivity<BookIntroPresenter>(), BookIntroView {
presenter.getIntro(mLink)
}

override fun isRegisterEventBus(): Boolean = true

@Subscribe(threadMode = ThreadMode.MAIN)
fun onReadRecordAddedEvent(event: ReadRecordAddedEvent) {
kotlin.run {
mAdapter.data.forEachIndexed { index, bookChapterBean ->
if (bookChapterBean.link == event.readRecordModel.link) {
bookChapterBean.time = event.readRecordModel.time
bookChapterBean.percent = event.readRecordModel.percentFloat
mAdapter.notifyItemChanged(index)
return@run
}
}
}
}

@Subscribe(threadMode = ThreadMode.MAIN)
fun onReadRecordUpdateEvent(event: ReadRecordUpdateEvent) {
kotlin.run {
mAdapter.data.forEachIndexed { index, bookChapterBean ->
if (bookChapterBean.link == event.link) {
bookChapterBean.time = event.time
bookChapterBean.percent = event.percent
mAdapter.notifyItemChanged(index)
return@run
}
}
}
}

override fun getBookIntroSuccess(bean: BookIntroBean) {
MultiStateUtils.toContent(msv)
ImageLoader.userIcon(riv_book_img, bean.img)
Expand Down
Loading

0 comments on commit 5b116af

Please sign in to comment.