Jetpack compose and Kotlin, dynamic UI losing values on recomp - kotlin

I am making a dynamic UI using kotlin and Jetpack compose and storing the information in an object box database.
The aim is that i will have a composable that starts off with 1 initial item that is empty and when the contents of the textbox have been filled in would allow the red "+" button to be clicked and then another textfield would appear. These values will need to be able to be edited constantly all the way until the final composable value is stored. The button changes colour currently and the states are fine with the button so i can add and remove rows
The data comes in as a string and is converted into a Hashmap<Int, String>. The int is used to store the position in the map being edited and the string would be the text value.
Using log messages i see that the information is updated in the list and for recomp sake i instantly store the value of the edited list in a converted json string.
At the moment:
When i scroll past the composable it resets and looks like the initial state (even if i have added multiple rows)
Log messages show that my hashmap has the values from before e.g. {"0":"asdfdsa"} but the previous positions are ignored and as the previous information would still be present but not shown on the UI when i enter it into the first field again (the others are not visible at the time) {"0":"asdfdsa","0":"hello"}. This would later cause an error when trying to save new data to the list because of the duplicate key
In the composables my hashmap is called textFields and is defined like this. Number is used to determine how many textfields to draw on the screen
val textFields = remember { getDataStringToMap(data.dataItem.dataValue) }
val number = remember { mutableStateOf(textFields.size) }
the method to getDataStringToMap is created like this
private fun getDataMapToString(textFieldsMap: HashMap<Int, String>): String {
val gson = Gson()
val newMap = hashMapOf<Int, String>()
for (value in textFieldsMap){
if (value.value .isNotBlank()){
newMap[value.key] = value.value
}
}
return gson.toJson(newMap)
}
and the method to getDataStringToMap is created like this (I explicitly define the empty hashmap type because its more readable for me if i can see it)
private fun getDataStringToMap(textsFieldsString: String): HashMap<Int, String> {
val gson = Gson()
return if (textsFieldsString.isBlank()) {
hashMapOf<Int, String>(0 to "")
} else {
val mapType = HashMap<Int, String>().javaClass
gson.fromJson(textsFieldsString, mapType)
}
the composables for the textfields are called like this
items(number.value) { index ->
listItem(
itemValue = textFields[index].orEmpty(),
changeValue = {
textFields[index] = it
setDataValue(getDataMapToString(textFields))
},
addItem = {
columnHeight.value += itemHeight
scope.launch {
scrollState.animateScrollBy(itemHeight)
}
},
deleteItem = {
columnHeight.value -= itemHeight
scope.launch {
scrollState.animateScrollBy(-itemHeight)
}
},
lastItem = index == number.value - 1,
index = index
)
}
Edited 30/12/2022
Answer from #Arthur Kasparian solved issues. Change to rememberSaveable retains the UiState even on scroll and recomp.
Now just to sort out which specific elements are removed and shown after :D

The problem is that remember alone does not save values on configuration changes, whereas rememberSaveable does.
You can read more about this here.

Related

Paging adapter unable to receive updated data

I am currently building a fragment, and within the fragment contains 2 paging adapter sharing the same data. When I update the data, only one of the paging adapter receives the updated data while the other does not.
On first start up. for reference (backdrop - top adapter/viewpager, poster - bottom adapter/viewpager)
first item =
second item =
third item =
when I change the movie category, only the bottom paging adapter receive the updated data
updated first item =
updated second item =
updated third item =
as seen in the image, the bottom paging adapter have successfully updated its image while the top paging adapter does not
additional information:
I am using Remote Mediator to store network data to ROOM Database.
Both top and bottom list is displayed using viewpager2, page transformer is applied to both viewpager. To add on, top viewpager scroll is dependent on the bottom viewpager (i.e. top viewpager will only scroll if bottom view pager scrolls).
depending on which paging adapter's submitData function is called first, its data will be updated, while the paging adapter after it won't update its data.
for the case below, the bottom viewPager(poster) will be updated while the top viewPager(backdrop) won't be updated.
collectLatestLifecycleFlow(viewModel.movieList) { pagingData ->
posterPagingAdapter.submitData(pagingData)
backdropPagingAdapter.submitData(pagingData)
}
I expect both paging adapter to be updated when I update the movie category.
so far as a temporary solution I created two flow collectors to collect the data so that both viewpager can update their data, however this is inefficient as it will do another Api Call which is redundant.
collectLatestLifecycleFlow(viewModel.movieList) { pagingData ->
backdropPagingAdapter.submitData(pagingData)
}
collectLatestLifecycleFlow(viewModel.movieList) { pagingData ->
posterPagingAdapter.submitData(pagingData)
}
below is the code I use to in ViewModel to get the data
val movieList = selectedMovieCategory.flatMapLatest {
Timber.i("selected category: $it")
when (it) {
MoviePagingCategory.NOW_PLAYING.categoryName -> {
moviesUseCase.getNowPlayingPagingData(loadSinglePage = true)
}
MoviePagingCategory.POPULAR.categoryName -> {
moviesUseCase.getPopularMoviesPagingData(loadSinglePage = true)
}
MoviePagingCategory.TRENDING.categoryName -> {
moviesUseCase.getTrendingMoviesPagingData(loadSinglePage = true)
}
else -> throw Exception("No listed category")
}.cachedIn(viewModelScope)
}
for PagingAdapter's diff util. do note that id here is a manually generated id instead of movieId provided by the Api. the reason for this is to store multiple movie types in single room table.
companion object DiffUtilCallback : DiffUtil.ItemCallback<Result>() {
override fun areItemsTheSame(oldItem: Result, newItem: Result): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Result, newItem: Result): Boolean {
return oldItem == newItem
}
}

Use filtered dataProvider contents when FileDownloader is called in Vaadin

I'm trying to download a csv file after applying filters to the DataProvider.
For some reason the filtered results are shown in the Grid, but the downloaded csv file still contains all data.
#AutoView
class FinancialTransactionsView : VerticalLayout(), View {
private val grid: Grid<FinancialTransaction>
private val yearField: ComboBox<Int>
private val dataProvider = DataProvider.ofCollection(FinancialTransaction.findAll())
private val fileDownloader: FileDownloader
init {
label("Financial Transactions") {
styleName = ValoTheme.LABEL_H1
}
yearField = comboBox("Select Year") {
setItems(listOf(2016, 2017, 2018))
addSelectionListener {
// Filter the data based on the selected year
if (it.value != it.oldValue) setDataProvider()
}
}
// Create FileDownloader and initialize with all contents in the DataProvider
fileDownloader = FileDownloader(createCsvResource())
val downloadButton = button("Download csv") {
styleName = ValoTheme.BUTTON_PRIMARY
onLeftClick {
// The idea here is to assign values from the filtered DataProvider to the FileDownloader
fileDownloader.fileDownloadResource = createCsvResource()
}
}
fileDownloader.extend(downloadButton)
fileDownloader.fileDownloadResource = createCsvResource()
grid = grid(dataProvider = dataProvider) {
expandRatio = 1f
setSizeFull()
addColumnFor(FinancialTransaction::companyId)
addColumnFor(FinancialTransaction::fiscalYear)
addColumnFor(FinancialTransaction::fiscalPeriod)
addColumnFor(FinancialTransaction::currency)
addColumnFor(FinancialTransaction::finalizedDebitAmountInCurrency)
addColumnFor(FinancialTransaction::finalizedCreditAmountInCurrency)
appendHeaderRow().generateFilterComponents(this, FinancialTransaction::class)
}
}
private fun createCsvResource(): StreamResource {
return StreamResource(StreamResource.StreamSource {
val csv = dataProvider.items.toList().toCsv()
try {
return#StreamSource csv.byteInputStream()
} catch (e: IOException) {
e.printStackTrace()
return#StreamSource null
}
}, "financial_transactions.csv")
}
private fun setDataProvider() {
dataProvider.clearFilters()
if (!yearField.isEmpty)
dataProvider.setFilterByValue(FinancialTransaction::fiscalYear, yearField.value)
}
}
toCsv() is an extension function List<FinancialTransaction> which returns a string containing csv data.
What can I do to get the filtered results in my csv file?
val csv = dataProvider.items.toList().toCsv()
I am not Kotlin guy, but I assume dataProvider.items is a shorthand to dataProvider.getItems() in Java, i.e. this method (and you use ListDataProvider)
https://vaadin.com/download/release/8.4/8.4.1/docs/api/com/vaadin/data/provider/ListDataProvider.html#getItems--
In Vaadin getItems() returns all items by passing all filters.
So instead you should do either of the following
dataProvider.fetch(..)
https://vaadin.com/download/release/8.4/8.4.1/docs/api/com/vaadin/data/provider/DataProvider.html#fetch-com.vaadin.data.provider.Query-
Where you give the filters you want to apply in the query, or
grid.getDataCommunicator.fetchItemsWithRange(..)
https://vaadin.com/download/release/8.4/8.4.1/docs/api/com/vaadin/data/provider/DataCommunicator.html#fetchItemsWithRange-int-int-
Which returns list of items with filters you have set applied, which I think is ideal for you
Thank you for using Vaadin-on-Kotlin!
I've just updated the Databases Guide which should hopefully answer all of your questions. If not, just let me know and I'll update the guides accordingly.
The ListDataProvider.items will not apply any filters and will always return all items.
You need to use the getAll() extension function in order to obey the filters set by the Grid.
This is now explained in the Exporting data from DataProviders chapter of the Databases Guide.
In your code, both the grid and the yearField will set the filter to the same data provider,
thus overwriting values set by each other. Please read the Chaining Data Providers chapter in the Databases Guide to learn how to AND multiple filters set by multiple components.
When you use private val dataProvider = DataProvider.ofCollection(FinancialTransaction.findAll()), that will load all transactions from the database in-memory. You can use a more memory-efficient way: private val dataProvider = FinancialTransaction.dataProvider (given that FinancialTransaction is an Entity)
Please let me know if this answers your questions. Thanks!

how to add Array index value in Kotlin?

first, I create empty Array(Kotlin) instance in companion object.
companion object {
var strarray: Array<String> = arrayOf()
var objectarray: LinkedHashMap<Int, List<Any>> = LinkedHashMap<Int, List<Any>>()
}
and I expected that I use empty array instance when read textString from CSV File.
fun csvFileToString():String {
val inputStream = File(Paths.get("").toAbsolutePath().toString()
.plus("/src/main/SampleCSVFile_2kb.csv")).inputStream()
val reader = inputStream.bufferedReader()
var iterator = reader.lineSequence().iterator()
var index:Int = 1;
while (iterator.hasNext()){
var lineText:String = iterator.next()
strarray.set(index, lineText)
index++
}
return ""
}
but when I run that source code
a.csvFileToString()
println(CsvParser.strarray)
occured exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
strarray.set(index, lineText) <<<<<<<<< because of this line
can I use Array(from kotlin collection) like ArrayList(from java collection)?
You can add a new item to an array using +=, for example: item += item
private var songs: Array<String> = arrayOf()
fun add(input: String) {
songs += input
}
Size of Array is defined at its creation and cannot be modified - in your example it equals 0.
If you want to create Array with dynamic size you should use ArrayList.
arrayOf gives you an array. Arrays have fixed length even in Java.
listOf gives you an immutable list. You cannot add or remove items in this list.
What you're looking for is mutableListOf<String>.
In your current approach, reusing a member property, don't forget to clear the list before every use.
Your code can be further simplified (and improved) like so:
out.clear()
inputStream.bufferedReader().use { reader -> // Use takes care of closing reader.
val lines = reader.lineSequence()
out.addAll(lines) // MutableList can add all from sequence.
}
Now imagine you wanted to consume the output list but needed to parse another file at the same time.
Consider working towards a pure function (no side effects, for now no accessing member properties) and simplifying it even further:
fun csvFileToString(): String { // Now method returns something useful.
val inputStream = File(Paths.get("").toAbsolutePath().toString()
.plus("/src/main/SampleCSVFile_2kb.csv")).inputStream()
inputStream.bufferedReader().use {
return it.lineSequence().joinToString("\n")
}
}
In this case we can totally skip the lists and arrays and just read the text:
inputStream.bufferedReader().use {
return it.readText()
}
I'm assuming that's what you wanted in the first place.
Kotlin has a lot of useful extension functions built-in. Look for them first.

Dynamic table columns

How should I proceed when I want to generate table from list of lists which contains only strings(ex. data from csv). Names of columns don't matter. From all examples provided I saw only binding table items to specific model(which doesn't fit there as I have unknown number and names of columns).
If you already know the column names and data type, I would suggest to hard code that. If you know nothing about the format and simply want to create a TableView with completely dynamic columns, you can use the index in the csv data as an extractor to create StringProperty values for your data:
class MyView : View() {
val data = FXCollections.observableArrayList<List<String>>()
val csvController: CsvController by inject()
init {
runAsync {
csvController.loadData()
} ui { entries ->
// Generate columns based on the first row
entries.first().forEachIndexed { colIndex, name ->
root.column(name, String::class) {
value { row ->
SimpleStringProperty(row.value[colIndex])
}
}
}
// Assign the extracted entries to our list, skip first row
data.setAll(entries.drop(1))
}
}
override val root = tableview(data)
}
class CsvController : Controller() {
// Load data from CSV file here, we'll use som static data
// where the first row is the headers
fun loadData() = listOf(
listOf("Name", "Age"),
listOf("John", "42"),
listOf("Jane", "24")
)
}
This approach would only be good for visualizing the data in a CSV file. If you need to edit or manipulate the data, knowledge of the data types up front would yield a less flimsy application IMO :)

JavaFX Check Cell background of specific Cell (random access)

I just started to develop a JavaFX application. Maybe I didn't get how JavaFX uses the TableView and I should use something different instead.
Currently my TableView displays data in multiple columns an when I double-click a cell the background color changes (by setCellFactory(customFactory)).
Now I want to access different cells of the table by using indices (column,row) and checking the background color.
The cells with a changed background color should be stored after a certain button was clicked.
I would like to get every cell with changed background(get celltext) for each row and store this for later use in a data structure like a Map>.
Would be really nice if somebody can give me a hint. Thank for your Help.
I suppose, you are adding an EventHandler to the TableCell, which is returned by your customFactory. This EventHandler is handling the doubleclick-event and sets the background color, right?
This handler has access to the parameter which is passed to the Callbacks/CustomFactories call-method, which contains the model-bean of the current row. You could set a flag or the columns name in that model-bean when a doubleClickEvent occurs.
Then
after a certain button was clicked
you can get your info, by checking the tables items. The row-index of each item is equivalent to the index of this item in the List of TableView#getItems
Also have a look at http://controlsfx.bitbucket.org/org/controlsfx/control/spreadsheet/SpreadsheetView.html if you need more TableFunctions.
EDITED
This is a code-example:
The Model-Bean used in TableView:
class Model {
private String propertyA;
private String propertyB;
#lombok.Getter
private Set<String> propertiesClicked = new HashSet<>();
The javafx-controls, annotate them with #FXML if you use FXMLs:
private TableView<Model> tableView;
private TableColumn<Model, String> propertyAColumn;
private TableColumn<Model, String> propertyBColumn;
and the the CellFactory. Create a more generic CellFactory if you need it for multiple columns:
propertyAColumn.setCellFactory((value) -> {
TableCell<Model, String> tableCell = new TableCell<Model, String>() {
//Override the Methods which you need
};
tableCell.setOnMouseClicked((mouseEvent) -> {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2 && !tableCell.getStyleClass().contains("buttonClicked")) {
tableCell.getStyleClass().add("buttonClicked");
tableView.getSelectionModel().getSelectedItem().getPropertiesClicked().add("propertyA");
}
}
});
return tableCell;
});