【发布时间】:2020-01-14 04:02:40
【问题描述】:
我已经为historyactivity设置了roomdatabase,我可以使用insert方法。 现在,当我单击我的历史活动时,数据仍然出现在 recyclerview 项目中。 但是我想在关闭构建应用程序时重置数据。我该怎么做?任何人都可以帮忙吗? 在我的 DAO 中,你可以看到有趣的 deleteAll(),那么当我关闭我的应用程序时如何使用它? 历史.kt
@Entity(tableName = "history")
class History(@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name= "item") var item:String?,
@ColumnInfo(name = "title") var title:String?,
@ColumnInfo(name = "price") var price:Int?,
@ColumnInfo(name = "Image") var Image:String?
) {
constructor(): this(null,"","",0,"")
}
@Dao
interface HistoryDao {
@Query("SELECT * FROM history")
fun getAll(): List<History>
@Insert(onConflict = REPLACE )
fun insert(history: History)
@Query("DELETE from history")
fun deleteAll(): List<History>
}
历史数据库
@Database(entities = [History::class], version = 3)
abstract class HistoryDB: RoomDatabase() {
abstract fun HistoryDB(): HistoryDao
companion object {
private var INSTANCE: HistoryDB?=null
fun getInstance(context: Context): HistoryDB? {
if (INSTANCE == null) {
synchronized(HistoryDB::class) {
INSTANCE = Room.databaseBuilder(context.applicationContext,
HistoryDB::class.java, "history.db")
.fallbackToDestructiveMigration()
.build()
}
}
return INSTANCE
}
fun destoryInstance() {
INSTANCE = null
}
}
}
历史活动
class HistoryActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener {
private var historyDb: HistoryDB? = null
private var historyList = listOf<History>()
lateinit var adapter: HistoryitemReclycerViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_history)
historyDb = HistoryDB.getInstance(this)
adapter = HistoryitemReclycerViewAdapter(this, historyList)
val r = Runnable {
try {
historyList = historyDb?.HistoryDB()?.getAll()!!
adapter = HistoryitemReclycerViewAdapter(this, historyList)
adapter.notifyDataSetChanged()
swipeRefreshLo.setOnRefreshListener(this)
recyclerview.adapter = adapter
recyclerview.layoutManager = LinearLayoutManager(this)
} catch (e: Exception) {
}
}
val thread = Thread(r)
thread.start()
}
override fun onRefresh() {
swipeRefreshLo.isRefreshing = false
}
override fun onDestroy() {
HistoryDB.destoryInstance()
historyDb =null
super.onDestroy()
}
}
【问题讨论】:
-
你检查我的答案了吗?如果它对你有用,请接受它
标签: android-studio kotlin android-room