|
| 1 | +package com.google.ai.sample.util |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import android.content.SharedPreferences |
| 5 | +import com.google.ai.sample.feature.multimodal.PhotoParticipant |
| 6 | +import com.google.ai.sample.feature.multimodal.PhotoReasoningMessage |
| 7 | +import com.google.gson.Gson |
| 8 | +import com.google.gson.reflect.TypeToken |
| 9 | + |
| 10 | +/** |
| 11 | + * Utility class for persisting chat history across app restarts |
| 12 | + */ |
| 13 | +object ChatHistoryPreferences { |
| 14 | + private const val PREFS_NAME = "chat_history_prefs" |
| 15 | + private const val KEY_CHAT_MESSAGES = "chat_messages" |
| 16 | + |
| 17 | + private val gson = Gson() |
| 18 | + |
| 19 | + /** |
| 20 | + * Save chat messages to SharedPreferences |
| 21 | + */ |
| 22 | + fun saveChatMessages(context: Context, messages: List<PhotoReasoningMessage>) { |
| 23 | + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) |
| 24 | + val editor = prefs.edit() |
| 25 | + |
| 26 | + val json = gson.toJson(messages) |
| 27 | + editor.putString(KEY_CHAT_MESSAGES, json) |
| 28 | + editor.apply() |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Load chat messages from SharedPreferences |
| 33 | + */ |
| 34 | + fun loadChatMessages(context: Context): List<PhotoReasoningMessage> { |
| 35 | + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) |
| 36 | + val json = prefs.getString(KEY_CHAT_MESSAGES, null) ?: return emptyList() |
| 37 | + |
| 38 | + val type = object : TypeToken<List<PhotoReasoningMessage>>() {}.type |
| 39 | + return try { |
| 40 | + gson.fromJson(json, type) |
| 41 | + } catch (e: Exception) { |
| 42 | + emptyList() |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Clear all chat messages from SharedPreferences |
| 48 | + */ |
| 49 | + fun clearChatMessages(context: Context) { |
| 50 | + val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) |
| 51 | + val editor = prefs.edit() |
| 52 | + editor.remove(KEY_CHAT_MESSAGES) |
| 53 | + editor.apply() |
| 54 | + } |
| 55 | +} |
0 commit comments