所以我有一个问题,我必须在学校开发一款聊天应用程序,该应用程序具有一项功能,可以让我像在 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);
}
也许有人可以给我指点。
最佳答案
有一种最佳方法可以在用户离线(无互联网连接)时使用 Firebase 实时数据库制作聊天应用程序。 Firebase 创建了一个本地数据库,并将所有详细信息存储在本地,并显示您的用户详细信息和消息。您不需要创建单独的数据库。点击此链接了解 Firebase 实时数据库:- https://firebase.google.com/docs/database/android/start/?gclid=EAIaIQobChMInMag3qiV4wIVAh4rCh2fJQWAEAAYASABEgIfFPD_BwE
关于java - 如何持久保存数据以便我可以离线使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56841490/