File caching: Basic

This section shows you how to build a simple cache that stores a user's most recent messages and channels. This cache can be used to load data when a user views their channel list, or enters a channel to view their message history. Implementing even a basic cache such as this can greatly improve user experience, as users no longer encounter empty lists of channels or messages when their connectivity is unstable.

In the steps described below, we create a file per channel in the application's cache directory, write serialized data into the file to store a set amount of recent messages, configure the app to first load messages from the cache, and then finally replace them when the newest results are successfully fetched from the servers.


Serialize and deserialize SendBird objects

To store SendBird objects such as messages, channels, and users in local storage, we provide serialization and deserialization methods through our SDK. Use serialize() to convert a SendBird object to binary data, which can then be natively stored in a file.

byte[] baseMessage.serialize()
BaseMessage BaseMessage.buildFromSerializedData(byte[] data)

byte[] baseChannel.serialize()
BaseChannel BaseChannel.buildFromSerializedData(byte[] data)

Save serialized messages

With serialization, you can store a channel and its most recent messages in a file. In this case, we are encoding the binary serialized data into a Base64 string. then storing each item in a new line. Normally, save data when onStop() is called in your user's chat screen.

public void save() {
    try {
        StringBuilder sb = new StringBuilder();
        if (mChannel != null) {
            // Convert current channel instance into a string.
            sb.append(Base64.encodeToString(mChannel.serialize(), Base64.DEFAULT | Base64.NO_WRAP));

            // Converts up to 100 messages within the channel into a string.
            BaseMessage message = null;
            for (int i = 0; i < Math.min(mMessageList.size(), 100); i++) {
                message = mMessageList.get(i);
                sb.append("\n");
                sb.append(Base64.encodeToString(message.serialize(), Base64.DEFAULT | Base64.NO_WRAP));
            }

            String data = sb.toString();
            String md5 = TextUtils.generateMD5(data);

            // Create a file within the app's cache directory.
            File appDir = new File(mContext.getCacheDir(), SendBird.getApplicationId());
            appDir.mkdirs();

            // Create a data file and a hash file within the directory.
            File dataFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + mChannel.getUrl()) + ".data");
            File hashFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + mChannel.getUrl()) + ".hash");

            try {
                String content = FileUtils.loadFromFile(hashFile);
                // If data has not been changed, do not save.
                if(md5.equals(content)) {
                    return;
                }
            } catch(IOException e) {
                // File not found. Save the data.
            }

            FileUtils.saveToFile(dataFile, data);
            FileUtils.saveToFile(hashFile, md5);
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
}

Note: In this case, MD5 hashing is used to generate a hash file for each stored data file. Using this hash file, you can check if the newly generated data differs from the one already stored in the cache, preventing unnecessary overwriting.


Load messages with deseralization

When your user enters a chat to view their message history, load saved messages from the cache.

public void load(String channelUrl) {
    try {
        File appDir = new File(mContext.getCacheDir(), SendBird.getApplicationId());
        appDir.mkdirs();

        File dataFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + channelUrl) + ".data");

        String content = FileUtils.loadFromFile(dataFile);
        String [] dataArray = content.split("\n");

        // Load the channel instance.
        mChannel = (GroupChannel) GroupChannel.buildFromSerializedData(Base64.decode(dataArray[0], Base64.DEFAULT | Base64.NO_WRAP));

        // Add the loaded messages to the currently displayed message list.
        for(int i = 1; i < dataArray.length; i++) {
            mMessageList.add(BaseMessage.buildFromSerializedData(Base64.decode(dataArray[i], Base64.DEFAULT | Base64.NO_WRAP)));
        }

        notifyDataSetChanged();
    } catch(Exception e) {
        // Nothing to load.
    }
}

After receiving an updated message list from the SendBird servers, clear the current message list and replace it with the updated list. In effect, messages from the cache are overwritten almost instantly if the user's connection is normal.


Save and load channels

The process of caching channels is identical to caching messages. For the sake of brevity, an implementation is provided without additional explanations.

// Saving channels
public void save() {
    try {
        StringBuilder sb = new StringBuilder();
        if (mChannelList != null && mChannelList.size() > 0) {
            // Convert current channel into a String.
            GroupChannel channel = null;
            for (int i = 0; i < Math.min(mChannelList.size(), 100); i++) {
                channel = mChannelList.get(i);
                sb.append("\n");
                sb.append(Base64.encodeToString(channel.serialize(), Base64.DEFAULT | Base64.NO_WRAP));
            }
            // Remove first newline.
            sb.delete(0, 1);

            String data = sb.toString();
            String md5 = TextUtils.generateMD5(data);

            // Save the data into file.
            File appDir = new File(mContext.getCacheDir(), SendBird.getApplicationId());
            appDir.mkdirs();

            File hashFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + "channel_list") + ".hash");
            File dataFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + "channel_list") + ".data");

            try {
                String content = FileUtils.loadFromFile(hashFile);
                // If data has not been changed, do not save.
                if(md5.equals(content)) {
                    return;
                }
            } catch(IOException e) {
                // File not found. Save the data.
            }

            FileUtils.saveToFile(dataFile, data);
            FileUtils.saveToFile(hashFile, md5);
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
}

// Loading channels
public void load() {
    try {
        File appDir = new File(mContext.getCacheDir(), SendBird.getApplicationId());
        appDir.mkdirs();

        File dataFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + "channel_list") + ".data");

        String content = FileUtils.loadFromFile(dataFile);
        String [] dataArray = content.split("\n");

        // Add the loaded channels to the currently displayed channel list.
        for(int i = 0; i < dataArray.length; i++) {
            mChannelList.add((GroupChannel) BaseChannel.buildFromSerializedData(Base64.decode(dataArray[i], Base64.DEFAULT | Base64.NO_WRAP)));
        }

        notifyDataSetChanged();
    } catch(Exception e) {
        // Nothing to load.
    }
}