最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Problem with saving a mutable list of strings to an object class in Kotlin. (Android Studio) - Stack Overflow

programmeradmin1浏览0评论

I am making an Android app, and I need a little help. I am saving 4 things to a data storage class: Strings (chat name), lists of Strings (full chat), lists of ChatMessages (summarized chats), and Integers (summarized amounts). The data storage class is usedd for the saving and loading of chats, and everything works, except the loading of the full chat. I will attach the code and log output below.

Object Class

package com.example.worldcrafter.ui

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

object ChatStorage {
    private val names = mutableListOf<String>()
    private val textStorage = mutableListOf<MutableList<String>>()
    private val summarizedStorage = mutableListOf<MutableList<ChatMessage>>()
    private val summarizedAmount = mutableListOf<Int>()

    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<String>, id: Int? = null) {
        println("WRLD - Adding text: $text")
        if (id != null) {
            textStorage[id] = text
        } else {
            textStorage.add(text)
        }
    }

    fun addSummarized(summarized: MutableList<ChatMessage>, 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<String>, summarized: MutableList<ChatMessage>, 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<String> {
        println("WRLD - Getting text at index: $index. Text: ${textStorage[index]}")
        return textStorage[index]
    }

    fun getSummarized(index: Int): MutableList<ChatMessage> {
        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<RecyclerView>(R.id.recyclerViewOfSavedChats)
    val buttonLabels = mutableListOf<String>()

    // 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<RecyclerView>(R.id.recyclerView)
    val chatAdapter = ChatAdapter(conversation) // Use ChatAdapter directly
    recyclerView.layoutManager = LinearLayoutManager(this)
    recyclerView.adapter = chatAdapter

    // Reference to TextInputEditText
    val inputEditText = findViewById<TextInputEditText>(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
}

Logging Output:

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?

Anyone have any idea as to why this is happening?

I am making an Android app, and I need a little help. I am saving 4 things to a data storage class: Strings (chat name), lists of Strings (full chat), lists of ChatMessages (summarized chats), and Integers (summarized amounts). The data storage class is usedd for the saving and loading of chats, and everything works, except the loading of the full chat. I will attach the code and log output below.

Object Class

package com.example.worldcrafter.ui

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

object ChatStorage {
    private val names = mutableListOf<String>()
    private val textStorage = mutableListOf<MutableList<String>>()
    private val summarizedStorage = mutableListOf<MutableList<ChatMessage>>()
    private val summarizedAmount = mutableListOf<Int>()

    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<String>, id: Int? = null) {
        println("WRLD - Adding text: $text")
        if (id != null) {
            textStorage[id] = text
        } else {
            textStorage.add(text)
        }
    }

    fun addSummarized(summarized: MutableList<ChatMessage>, 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<String>, summarized: MutableList<ChatMessage>, 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<String> {
        println("WRLD - Getting text at index: $index. Text: ${textStorage[index]}")
        return textStorage[index]
    }

    fun getSummarized(index: Int): MutableList<ChatMessage> {
        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<RecyclerView>(R.id.recyclerViewOfSavedChats)
    val buttonLabels = mutableListOf<String>()

    // 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<RecyclerView>(R.id.recyclerView)
    val chatAdapter = ChatAdapter(conversation) // Use ChatAdapter directly
    recyclerView.layoutManager = LinearLayoutManager(this)
    recyclerView.adapter = chatAdapter

    // Reference to TextInputEditText
    val inputEditText = findViewById<TextInputEditText>(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
}

Logging Output:

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?

Anyone have any idea as to why this is happening?

Share Improve this question asked Feb 5 at 17:03 Alexander MailyantsAlexander Mailyants 12 bronze badges 1
  • Are you sure you are not mutating the MutableList after calling addText? Passing a MutableList might not be the best approach as it can be edited anywhere else in the app without triggering your log messages – Juan Cruz Soler Commented Feb 5 at 18:24
Add a comment  | 

1 Answer 1

Reset to default 0

answer by u/tetrahedral on Reddit:

My hunch is that you are passing the text back as a MutableList somewhere and calling .clear() on it without realizing that it’s a reference to the storage. Modify getText and addText to copy into a new array and see if the problem goes away.

I was creating an alias to the mutableList when I was passing it as a parameter. when I called .clear() on it, the list was deleted in both files.

发布评论

评论列表(0)

  1. 暂无评论