Issue
I am new to Kotlin, I have this Kotlin code, the loaded data is not displayed at first but after navigating to another activity and coming back the data appears.
In online I have checked they said to add notifyOnChnaged but I am unable to implement it, If you know how to add notifyOnChanged
or any other solution please help me out.
class SecretsActivity : AppCompatActivity() {
lateinit var bind : ActivitySecretsBinding
override fun onCreate(savedInstanceState: Bundle?) {
val secretsList = firebaseSecretsData()
super.onCreate(savedInstanceState)
bind = ActivitySecretsBinding.inflate(layoutInflater)
setContentView(bind.root)
bind.secretsRecyclerView.adapter = SecretsAdapter(secretsList)
bind.secretsRecyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
bind.secretsRecyclerView.setHasFixedSize(true)
bind.secretsRecyclerView.adapter = SecretsAdapter(secretsList)
bind.ButtonWrite.setOnClickListener {
val intent = Intent(this, WriteActivity::class.java)
startActivity(intent)
overridePendingTransition(R.transition.fadein, R.transition.fadeout)
finish()
}
}
override fun onBackPressed() {
super.onBackPressed()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
overridePendingTransition(R.transition.fadein, R.transition.fadeout)
finish()
}
private fun firebaseSecretsData() : List<SecretsModel>{
val list = ArrayList<SecretsModel>()
val dbref = FirebaseDatabase.getInstance().getReference("Secrets")
dbref.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot.exists()){
for(i in snapshot.children){
val item = SecretsModel(i.value.toString())
list+=item
}
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
return list
}
}
Solution
//Initialize this first
val myAdapter = SecretsAdapter(secretsList)
. . . . .
private fun firebaseSecretsData() : List<SecretsModel>{
val list = ArrayList<SecretsModel>()
val dbref =
FirebaseDatabase.getInstance().getReference("Secrets")
dbref.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot.exists()){
for(i in snapshot.children){
val item = SecretsModel(i.value.toString())
list+=item
}
//Add this code
myAdapter.notifyDataSetChanged()
}
}
. . . . .
Moreover, you should use DiffUtil
if possible for performance reasons.
Answered By - RaBaKa 78