Проблема с сохранением изменяемого списка строк в класс объекта в Котлине. (Android Studio)Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Проблема с сохранением изменяемого списка строк в класс объекта в Котлине. (Android Studio)

Сообщение Anonymous »

Я делаю приложение для Android, и мне нужна небольшая помощь. Я сохраняю 4 вещи в классе хранения данных: строки (имя чата), списки строк (полный чат), списки Chatmessages (суммированные чаты) и целые числа (суммированные суммы). Класс хранения данных используется для сохранения и загрузки чатов, и все работает, кроме загрузки полного чата. Я прикреплю код и вывод журнала.

Код: Выделить всё

package com.example.worldcrafter.ui

import com.aallam.openai.api.chat.ChatMessage

object ChatStorage {
private val names = mutableListOf()
private val textStorage = mutableListOf()
private val summarizedStorage = mutableListOf()
private val summarizedAmount = mutableListOf()

fun addName(name: String, id: Int? = null) {
println("WRLD - Adding name: $name")
if (id != null) {
names[id] = name
} else {
names.add(name)
}
}

fun addText(text: MutableList, id: Int? = null) {
println("WRLD - Adding text: $text")
if (id != null) {
textStorage[id] = text
} else {
textStorage.add(text)
}
}

fun addSummarized(summarized: MutableList, id: Int? = null) {
println("WRLD - Adding summarized: $summarized")
if (id != null) {
summarizedStorage[id] = summarized
} else {
summarizedStorage.add(summarized)
}
}

fun addSummarizedAmount(amount: Int, id: Int? = null) {
println("WRLD - Adding summarized amount: $amount")
if (id != null) {
summarizedAmount[id] = amount
} else {
summarizedAmount.add(amount)
}
}

fun makeSave(name: String, text: MutableList, summarized: MutableList, summarizedAmt: Int, id: Int? = null) {
if (id != null) {
addName(name, id)
addText(text, id)
addSummarized(summarized, id)
addSummarizedAmount(summarizedAmt, id)
} else {
addName(name)
addText(text)
addSummarized(summarized)
addSummarizedAmount(summarizedAmt)
}
println("WRLD - Save Complete.")
}

fun getIDByName(str: String): Int? {
println("WRLD - Getting ID by name: $str")
for (i in 0 until names.size) {
if (names[i] == str) {
return i
}
}
return null
}

fun getName(index: Int): String {
println("WRLD - Getting name at index: $index. Name: ${names[index]}")
return names[index]
}

fun getText(index: Int): MutableList {
println("WRLD - Getting text at index: $index. Text: ${textStorage[index]}")
return textStorage[index]
}

fun getSummarized(index: Int): MutableList {
println("WRLD - Getting summarized at index: $index. Summarized: ${summarizedStorage[index]}")
return summarizedStorage[index]
}

fun getSummarizedAmount(index: Int): Int {
println("WRLD - Getting summarized amount at index: $index.  Summarized amount: ${summarizedAmount[index]}")
return summarizedAmount[index]
}

fun getSize(): Int {
println("WRLD - Chat storage size: ${names.size}")
return names.size
}

fun deleteSave(index: Int) {
println("WRLD - Deleting save at index: $index")
names.removeAt(index)
textStorage.removeAt(index)
summarizedStorage.removeAt(index)
summarizedAmount.removeAt(index)
}

fun clear() {
println("WRLD - Clearing chat storage")
names.clear()
textStorage.clear()
summarizedStorage.clear()
summarizedAmount.clear()
}
}
mainactivity.kt

Код: Выделить всё

private fun initSavedChatsMenu() {
setupButton(R.id.btAdventure1) { switchLayout(LayoutType.CHAT) }
setupButton(R.id.btSettings1) { switchLayout(LayoutType.SETTINGS) }
val recyclerView = findViewById(R.id.recyclerViewOfSavedChats)
val buttonLabels = mutableListOf()

// Populate button labels from ChatStorage
for (i in 0 until ChatStorage.getSize()) {
buttonLabels.add(ChatStorage.getName(i))
}

// Initialize the adapter with the labels and a callback
val buttonAdapter = ButtonAdapter(buttonLabels) { label ->
// Handle button clicks here
// For example, switch to the chat layout
switchLayout(LayoutType.CHAT)
initChatMenu(true, label)
}
// Set up RecyclerView with the adapter and layout manager
recyclerView.adapter = buttonAdapter
recyclerView.layoutManager = LinearLayoutManager(this)
}

// Initialize the buttons in the Chat layout (ChatGPT[3])
private fun initChatMenu(load: Boolean = false, name: String = "") {
setupButton(R.id.btSavedChats2) { switchLayout(LayoutType.SAVED_CHATS) }
setupButton(R.id.btSettings2) { switchLayout(LayoutType.SETTINGS) }
conversation.clear()
summarized.clear()

// Set up RecyclerView and Adapter
val recyclerView = findViewById(R.id.recyclerView)
val chatAdapter = ChatAdapter(conversation) // Use ChatAdapter directly
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = chatAdapter

// Reference to TextInputEditText
val inputEditText = findViewById(R.id.textInputEditText)

if (!load) {

//irrelevant, the code block that was here handles new chat initialization

}
} else {
// **Load saved conversation**
val chatIndex = ChatStorage.getIDByName(name) ?: return
conversation.clear()
val tempConversation = ChatStorage.getText(chatIndex)
summarized = ChatStorage.getSummarized(chatIndex)
summarizedAmt = ChatStorage.getSummarizedAmount(chatIndex)

// Notify adapter after adding all messages
for (i in 0 until conversation.size) {
conversation.add(tempConversation[i])
chatAdapter.notifyItemInserted(i)
recyclerView.smoothScrollToPosition(conversation.size - 1)
}

}

//also irrelevant, the code block that was here handles new chat input
}
Вывод журнала:

Код: Выделить всё

WRLD - Adding name: istfg if this doesn't workWRLD - Adding text: [Greetings, adventurer! ...]
WRLD - Adding summarized: [ChatMessage(role=Role(role=system), messageContent=TextContent(content=Commit this message to memory. ...]
WRLD - Adding summarized amount: 0
WRLD - Save Complete.
//the above five logs appear when a chat is saved.
WRLD - Chat storage size: 1
WRLD - Getting name at index: 0. Name: istfg if this doesn't work
//the above two logs appear when the saved chats menu is loaded.
WRLD - Getting ID by name: istfg if this doesn't work
WRLD - Getting text at index: 0. Text: []
WRLD - Getting summarized at index: 0. Summarized: [ChatMessage(role=Role(role=user), messageContent=TextContent(content=Commit this message to memory. ...]
WRLD - Getting summarized amount at index: 0. Summarized amount: 0
//the above four messages appear when a chat is loaded.

//as you can see, the "text at index: 0" is empty. the code that handle this manipulation of data is the exact same as that for the summarized version, except for the data type. what could be the cause of this issue?
У кого -нибудь есть представление о том, почему это происходит?

Подробнее здесь: https://stackoverflow.com/questions/794 ... kotlin-and
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»