Android (XMPP) Caching/Synchronising Messages in Chat Application
Asked Answered
V

1

9

Problem Description

I'm creating android chat application based on XMPP protocol. Smack is used as a XMPP Client library. In application messages are stored in SQLite database.

Question

How to implement message caching (ex. like it's done in Facebook messenger) ? In case if there are new messages on server download 20 and show to the user, if no show from local database. If user scroll up again check database and server and show next 20 messages.

Is there a open source example available?

Venue answered 25/9, 2017 at 19:5 Comment(2)
Usually when caching data that can be updated on the server causes the client to maintain an offset (counter/timestamp or something similar). These posts explain data sync patterns which you can use to come up with a protocol for your use case: #10829871 #11299708Sympetalous
I have done same project but used signalR as a communication. At first login I download latest message data (last 3day messages in my case) and store local sqlite db then reflect in view. If you scroll down i download more chunk data using rest api. For realtime messaging store message locally first then display in view.Delphinus
F
0

Use a combination of SQLite and XMPP MAM ext.


  1. Store the new messages in a database.
  2. Load and display the last x messages from local database.
  3. XMPP MAM extension will get information from server, from present, past, even if they were not present in the client's memory.
  4. Check database and the server when the user wants to view more messages.
  5. Cache eviction policy to reset/remove past messages from database to avoid memory usage.

Retrieve the last 20 messages using XMPP MAM ext:

int n = 20; // The number of messages to retrieve
MamManager mamManager = MamManager.getInstanceFor(connection);
MamQueryResult mamQueryResult = mamManager.queryArchive(n);
List<Forwarded> forwardedList = mamQueryResult.getForwardedMessages();
for (Forwarded forwarded : forwardedList) {
    Stanza stanza = forwarded.getForwardedStanza();
    if (stanza instanceof Message) {
        Message message = (Message) stanza;
        // Display the message to the user or process it as needed
    }
}

connection represents XMPP, n var represents the number of messages and mamManager.queryArchive(n) retrieves the last n message from MAM.

The if (stanza instanceof Messages) checks the Message stanzas as MAM can retrieve it like Presence.


See XEP-0313 for more information. Open Source examples can be good to check like Smack, SQLite and Pix-Art Messanger.

Fantoccini answered 29/3, 2023 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.