首页 > 解决方案 > 如何保存数据持久化以便我可以离线使用它们

问题描述

所以我有一个问题,我必须在学校做一个聊天应用程序,它的功能可以让我像在 WhatsApp 中一样离线查看我的旧对话。

在我立即关闭互联网后它会起作用,当我启动我的应用程序时,我可以看到我的对话,但一段时间后聊天不再加载。我在互联网上搜索了一下并阅读了我必须将聊天作为文件保存到内部存储中,但我该怎么做我找不到任何相关信息。

这是我在线和离线加载消息的代码

public void loadConversations() {
        boolean result;
        try {
            FileInputStream fileInputStream = getApplicationContext().openFileInput("CONVERSATIONS");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            this.conversations = (HashMap<String, ArrayList<Message>>) objectInputStream.readObject();
            objectInputStream.close();
            fileInputStream.close();
            result = true;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            result = false;
        }

        if (this.conversations == null) {
            this.conversations = new HashMap<>();
        }

        Log.d(TAG, "loadConversations result: " + result + " size: " + this.conversations.size());

    }

    public void persistConversations() {

        boolean result;
        try {
            FileOutputStream fileOutputStream = getApplicationContext().openFileOutput("CONVERSATIONS",getApplicationContext().MODE_PRIVATE);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(this.conversations);
            objectOutputStream.flush();
            objectOutputStream.close();
            fileOutputStream.close();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
            result = false;
        }

        Log.d(TAG, "persistConversations result: " + result);
    }

也许有人可以给我一个指针。

标签: javaandroid

解决方案


当用户离线(无互联网连接)时,最好的方法是使用 firebase 实时数据库制作聊天应用程序。Firebase 创建了一个本地数据库并将所有详细信息存储在本地并显示您的用户详细信息和您的消息。您不需要创建单独的数据库。按照此链接了解 Firebase 实时数据库:- https://firebase.google.com/docs/database/android/start/?gclid=EAAIQobChMInMag3qiV4wIVAh4rCh2fJQWAEAAYASABEgIfFPD_BwE


推荐阅读