Android Proto DataStore Mastery with Kotlin

Hello and welcome to another exciting tutorial! Today, we’ll delve into the world of Android Proto DataStore. If you’re still relying on SharedPreferences to store crucial values in your project, it’s strongly advised to make …

Android Proto DataStore with Kotlin

Hello and welcome to another exciting tutorial! Today, we’ll delve into the world of Android Proto DataStore. If you’re still relying on SharedPreferences to store crucial values in your project, it’s strongly advised to make the switch to DataStore. In this tutorial, we’ll explore the fundamentals of Proto DataStore, a powerful tool for saving complex types. Let’s get started!

For a detailed, step-by-step tutorial on utilizing Android Proto DataStore to store user session information, you can watch the accompanying video. Alternatively, if you prefer reading, continue with this post.

If you’ve landed here solely for the source code of this project, you can find it below.

Android Proto DataStore or Preferences Data Store

DataStore provides two options: Preferences and Proto DataStore. While this guide focuses on Proto DataStore, it’s essential to understand when to opt for Preferences DataStore. Preferences DataStore is akin to SharedPreferences, ideal for straightforward key-value pair persistence. On the other hand, if you need to persist typed objects to disk, Proto DataStore is the go-to choice.

Proto DataStore The Basics

Proto DataStore allows you to directly save Typed Objects, but it involves an additional step of creating an object schema using protobuf3 syntax.

Here’s a quick overview of the process for storing typed objects in Proto DataStore:

  1. Define your object schema using protobuf3 syntax.
  2. Create a DataStore object.
  3. Execute CRUD operations as needed.

Now, let’s put things into action. For this guide, feel free to use an existing Android project or create a new one.

Get the Dependencies on Place

To begin, you’ll need to acquire the DataStore dependency. The snippet below is specifically for Proto DataStore.

As mentioned earlier, to utilize Proto DataStore, class generation via protobuf schema is required. To facilitate this, we’ll need the following plugin and dependency.

First add the following plugin in your app-level build.gradle file.

Then add the following dependency.

To complete the class generation process, add the following configuration at the end of your app-level build.gradle file.

Now you can sync your project with gradle files.

Creating a Proto Schema

I’ll be persisting a basic object containing userId and authKey.

Place this content within a .proto file, for instance, user.proto, located inside the app/main/proto directory. If the proto directory is not present by default, create it. For a visual guide, you can refer to the video mentioned above to walk through this step.

To gain a more comprehensive understanding of proto syntax, refer to the official guide. I won’t delve into it extensively here.

Ensure to rebuild your project, as class generation occurs only after this step.

Acquiring the DataStore Instance

Define a UserSerializer

Before you create the DataStore instance, make sure to set up a serializer for your generated proto class. In this case, we’re using the User class, and the serializer, represented as an object, is named UserSerializer.

DataStore Object

Creating a DataStore object is straightforward. Simply establish an extension property of type DataStore<YourType>  within the Context. Delegate the initialization to the dataStore()  function.

Now, with the Context object, your DataStore is accessible from anywhere. Let’s delve into the detailed process of performing Create, Read, Update, and Delete (CRUD) operations on your DataStore. This will not only empower you to effectively manage data but also enhance the overall functionality of your application.

Create and Update

Creating and updating share a similar process. Whenever you update the data, the old value gets overwritten. Therefore, the steps to create and update are essentially the same.

Reading Persisted Values

Deleting

The operations are straightforward and self-explanatory. Simply access your DataStore instance with the context and carry out the necessary operation based on your requirements.

Now, let’s explore a real-world example. In my Mini Tales project, I’ve employed Android Proto DataStore to store essential information about the logged-in user, specifically the user ID and authentication key. Allow me to walk you through the steps involved in implementing this functionality, providing insights into how the power of Proto DataStore enhances user data management in practical applications.

Creating a User Session Handler

When a user logs into my application, I leverage Proto DataStore to save the user information. This functionality is encapsulated in an interface named “SessionHandler,” appropriately named for its role in managing user sessions. Let’s proceed by creating the SessionHandler interface, as demonstrated below.

Now I will create an implementation of this interface named DataStoreSesionHandler.

With the newly created DataStoreSessionHandler, we can seamlessly manage the session of a logged-in user within our application. This handler becomes a pivotal component for effectively handling and maintaining user sessions.

In a nutshell, diving into Android Proto DataStore with Kotlin makes handling data a breeze. You’ve learned the ropes, storing and retrieving typed objects effortlessly. That SessionHandler interface? It’s your go-to for managing user sessions. Give this guide a share with your developer buddies. Let’s level up our Android game together and make the most of Proto DataStore. Your shared knowledge makes us all stronger in the dev world! 🚀

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.

Expand Your Knowledge: Next Tutorial Picks

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Parth
Parth
2 months ago

Very well written and very nicely explained. Thanks for this post

1
0
Would love your thoughts, please comment.x
()
x