My recyclerView showing data repeatedly but I want the data only single time . I am fetching data from Room Database. and my Database store data perfectly when i saw it on Database Inspection. When I am scrolling recyclerview fetching duplicate data
class MainActivity2 : AppCompatActivity() {
lateinit var repository: Repository
lateinit var daoClass: DaoClass
lateinit var adapter: adapterClass
lateinit var databaseClass: DatabaseClass
lateinit var factory: ViewModelFactory
lateinit var viewmodelClass: ViewmodelClass
private var newList = mutableListOf<EntityClass>()
private var list = mutableListOf<EntityClass>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
databaseClass = DatabaseClass.getDatabase(this)
repository = Repository(databaseClass)
daoClass = databaseClass.getDao()
factory = ViewModelFactory(repository)
viewmodelClass = ViewModelProvider(this, factory)[ViewmodelClass::class.java]
insertData(list)
if (newList.isEmpty()) {
getAllData()
}
}
private fun getAllData() {
newList.clear()
viewmodelClass.getData().observe(this, Observer {
newList.addAll(it)
setRecyclerView()
})
}
private fun setRecyclerView() {
adapter = adapterClass(newList)
recyclerview.adapter = adapter
recyclerview.layoutManager = LinearLayoutManager(this)
}
private fun insertData(list: MutableList<EntityClass>) {
list.clear()
val item1 = EntityClass("01 March 2022", 5)
list.add(item1)
val item2 = EntityClass("02 March 2022", 7)
list.add(item2)
val item3 = EntityClass("03 March 2022", 4)
list.add(item3)
val item4 = EntityClass("04 March 2022", 0)
list.add(item4)
val item5 = EntityClass("05 March 2022", 6)
list.add(item5)
val item6 = EntityClass("06 March 2022", 5)
list.add(item6)
val item7 = EntityClass("07 March 2022", 6)
list.add(item7)
val item8 = EntityClass("08 March 2022", 4)
list.add(item8)
val item9 = EntityClass("09 March 2022", 3)
list.add(item9)
val item10 = EntityClass("10 March 2022", 9)
list.add(item10)
val item11 = EntityClass("11 March 2022", 3)
list.add(item11)
val item12 = EntityClass("12 March 2022", 5)
list.add(item12)
val item13 = EntityClass("13 March 2022", 0)
list.add(item13)
val item14 = EntityClass("14 March 2022", 10)
list.add(item14)
CoroutineScope(Main).launch {
viewmodelClass.deleteData()
list.forEach {
val datadb= EntityClass(it.Date,it.Sessions)
viewmodelClass.insertData(datadb)
}
}
}
}
I was expecting to save show only those 14 list items which I have inserted but it is showing those 14 items repeatedly.
CodePudding user response:
You need to clear list before adding data into list.
private fun getAllData() {
viewmodelClass.getData().observe(this, Observer {
newList.clear()
newList.addAll(it)
setRecyclerView()
})
}