LazyColumn doesn't updates

51 views Asked by At

My dataset undergoes multiple changes during program execution. However, the LazyColumn fails to reflect these changes and doesn't add the updated items.

in the main activity:


class MainActivity : ComponentActivity() {

    companion object {
        var myDataset = mutableListOf<MyNotification>()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NotyTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    val dbHelper = MyDatabaseHelper(this)
                    val db = dbHelper.readableDatabase
                    myDataset = readDB(db)
                    
                    MyApp(dataset = myDataset)
                }
            }
        }
    }
}

@Composable
fun MyApp(dataset: MutableList<MyNotification>) {
    val notifications = remember { dataset }

    LazyColumn {
        items(
            items = notifications,
            itemContent = { 
                NotificationItem(notification = it)
            })
    }
}

@Composable
fun NotificationItem(notification: MyNotification) {
    OutlinedCard {
        Text(text = notification.title)
        Text(text = notification.packageName)
        Text(text = SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(notification.postTime))
    }
}

in the other activity:

try {
                myDataset.add(MyNotification(sbn))
            } catch (e: Exception) {
                Log.v(thisTag, "An error occurred adding MyNotification in myDataset.")
            }

I want to specify that the try function succeeds.

I expected to see the LazyList changes in real when the dataset changes.

1

There are 1 answers

0
dev.tejasb On

There are many problems in your code.

First, you should not perform any IO operations on main thread which you're doing currently by reading from database. You should use ViewModel in which you should read your database and have a property to hold your list.

Second, you don't need to pass MutableList<MyNotification> to @Composable just pass List<MyNotification>. Also, remove this line val notifications = remember { dataset }. And use key parameter of items in LazyColumn.