Recognized by Clutch.co as a top-rated Mobile App Development Company.
folio3-mobile
US 408 365 4638
START YOUR PROJECT
  • Solutions
    • Apps Discovery Services
    • Team Augmentation
    • Enterprise
    • AR/VR
    • IoT
    • Wearables
    • Field Sales
    • On Demand Apps
  • Industries
    • Retail
    • Agriculture
    • Healthcare
    • Pharmaceutical & Life Sciences
    • Manufacturing
    • Automotive
    • Logistics
    • Education
  • Technologies
    • Native Mobile Apps
      • iOS
      • Android
    • Cross Platform Apps
      • React Native
      • Flutter
      • Ionic
      • Xamarin
      • NativeScript
      • Sencha
  • Portfolio
  • Blog
  • Contact Us
Menu
  • Solutions
    • Apps Discovery Services
    • Team Augmentation
    • Enterprise
    • AR/VR
    • IoT
    • Wearables
    • Field Sales
    • On Demand Apps
  • Industries
    • Retail
    • Agriculture
    • Healthcare
    • Pharmaceutical & Life Sciences
    • Manufacturing
    • Automotive
    • Logistics
    • Education
  • Technologies
    • Native Mobile Apps
      • iOS
      • Android
    • Cross Platform Apps
      • React Native
      • Flutter
      • Ionic
      • Xamarin
      • NativeScript
      • Sencha
  • Portfolio
  • Blog
  • Contact Us

Introduction to Jetpack DataStore – Alternative to SharedPreferences

Published by: Shehroz Asif | February 25, 2022 msaqlain
SCROLL AND BE AMAZED!
Home > Android App Development • App Development > Introduction to Jetpack DataStore – Alternative to SharedPreferences

Introduction

In mobile applications, some data has to be persisted to make the application startup faster, reduce network traffic or handle data completely offline. When we talk about data storage solutions for android, it is very common to think of SharedPreferences, it is a very simple/fast way of persisting data in our app and it has been here for a while, but now Jetpack DataStore comes as a possible replacement for SharedPreferences and it’s shortcomings.

In this article, we will be exploring Jetpack DataStore to store data in our Android application.

What is Jetpack DataStore?

Google’s definition:

“Jetpack DataStore is a data storage solution that allows you to store key-value pairs or typed objects with protocol buffers. DataStore uses Kotlin coroutines and Flow to store data asynchronously, consistently, and transactionally.”

DataStore provides 2 different implementations of Datastores:

  • Preferences DataStore
  • Proto DataStore

In short, the first one is the same as how SharedPreferences work, it is simpler to implement but has no type-safety. The second one uses protocol buffers to serialize the data, it has a more complex implementation, but it comes with many advantages. 

Preferences vs Proto DataStore

The main objective of Proto DataStore is similar to Preferences DataStore, but the Proto DataStore is able to store objects with custom data types, it does not use key-value pairs like Preferences DataStore, just returns the generated object in a Flow. The generated object’s type and structure depend on the schema of the .protoc file.

A few key features of Proto DataStore over Preferences DataStore are as follows:

  • Provides type safety out of the box
  • Able to define list inside protoc schema with repeated marked fields
  • Requires learning of a new serialization mechanism, which depends on Protobuf but it is worth the effort.
  • Protobuf is faster than XML and JSON serialization formats

Proto DataStore vs Room

If Proto DataStore is able to store objects with custom data types then you might be thinking “What to use Proto DataStore or Room?” or “Why not use Room?”. Well if you use Room to save only user’s data, you need to create a database with a table, and also need to implement the query and insert functions. It sounds really inconvenient, so in this case, the Proto DataStore can be a hassle-free approach.

In this article, we will be discussing and focusing on the Preferences DataStore and how to implement it.

Why Jetpack DataStore?

“If you’re currently using SharedPreferences to store data, consider migrating to DataStore instead.” – by Google

DataStore aims to replace SharedPreferences as it is thread-safe and non-blocking. The concept behind DataStore is also quite similar to SharedPreferences, it uses key-value pairs to store data. Following are the benefits of using DataStore over SharedPreferences:

Implementation (Preferences DataStore)

It’s time to get into the implementation part and see how to use Preferences DataStore in our application.

Step 1: Dependencies

To use Jetpack DataStore in our application we have to add the dependency in our app-level build.gradle file:

implementation “androidx.datastore:datastore-preferences:1.0.0”

Step 2: Create a DataStore

To create a Preferences DataStore, we can use the preferenceDataStore delegate. The delegate will ensure that we have a single instance of DataStore with that name in our application.

Step 3: Create keys to the DataStore

Unlike SharedPreferences where you can use hard-coded string keys to write and read the data, DataStore requires key objects. We will need to create a key object and this is how we can create it:

This looks like an extra step but it is actually very helpful as your project becomes bigger, this will enforce developers to have all the keys in a centralized location.

You can also create other types of PreferenceKeys:

  • booleanPreferenceKey(name: String)
  • doublePreferenceKey(name: String)
  • floatPreferenceKey(name: String)
  • intPreferenceKey(name: String)
  • longPreferenceKey(name: String)
  • stringPreferenceKey(name: String)
  • stringSetPreferenceKey(name: String)

Step 4: Write data to the DataStore

Now that we have created our DataStore and PreferencesKey, it’s time to write data to the DataStore, we need to call the edit() method, let’s see how we can do that:

Step 5: Reading data from DataStore

To read the data from DataStore, we need to access the “data” property from the datastore, the data property is a Flow<Preferences>, so we can either get the entire preferences or map it into the value we actually want:

Step 6: Handle Exceptions

With the flow object we can also catch exceptions:

Migrating from SharedPreferences

In order to be able to migrate from SharedPreferences to DataStore, we need to update the datastore builder to pass in a SharedPreferencesMigration to the list of migrations. DataStore will be able to migrate from SharedPreferences to DataStore automatically, for us. Migrations are run before any data access can occur in DataStore. 

Import SharedPreferencesMigration from androidx.datastore.preferences

That’s it! It’s that easy to migrate your data from SharedPreferences to DataStore. 🙂

Conclusion

Ideally DataStore is best to use with Kotlin and especially with coroutines. We don’t need to worry about if our application uses standard SharedPreferences because migration is provided by the DataStore API.

Because of the fact that DataStore handles data migration, guarantees data consistency, and handles data corruption, it is worth changing from SharedPreferences to DataStore.

Feel free to share your responses and feedback below.

Thanks for reading!


About Shehroz Asif

Newsletter

Search

Archives

  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • October 2021
  • September 2021
  • May 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • July 2019
  • May 2019
  • Categories

    • Android App Development
    • App Development
    • App Testing
    • Blog
    • Elasticsearch
    • flutter-app-development
    • IOT
    • React Native
    • Staff Augmentation

Recent Posts

  • Getting started with NgRx
  • Secure Mobile App Credentials in React Native
  • Bugs Count & Test Coverage
  • Introduction to Nessus Vulnerability Scanning Tool
  • Error Boundary in React Native

Tags

  • android
  • Automation
  • cross-platform
  • development
  • firebase
  • ios
  • QA
  • react-native
  • Testing
  • Test Script

Newsletter

Newsletter

Post navigation

Previous Automate React Native App Builds With Fastlane And Appcenter
Next Firebase Crashlytics Integration in React Native

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Schedule an appointment with our Mobile App Development Expert

    Footer Menu
    • Company
      • About Us
      • Portfolio
      • Blog
      • Careers
      • Contact Us
    • Solutions
      • Apps Discovery Services
      • Team Augmentation
      • Enterprise App Development
      • AR/VR Application Development
      • IoT Application Development
      • Wearables Apps Development
      • Field Sales
      • On-Demand Apps Development
    • Technologies
      • iOS
      • Android
      • React Native
      • Flutter
      • Ionic
      • Xamarin
      • NativeScript
      • HTML5
      • Sencha
    • Industries
      • Retail
      • Agriculture
      • Healthcare
      • Pharmaceutical
      • Manufacturing
      • Automotive
      • Logistics
      • Education

    US Office

    Belmont, California – 1301 Shoreway Road, Suite 160, Belmont, CA 94002

    Pleasanton, California – 6701 Koll Center Parkway, #250 Pleasanton, CA 94566

    Tel: +1 408 365 4638
    Support: +1 (408) 512 1812

    Mexico Office

    Amado Nervo #2200, Edificio Esfera 1 piso 4, Col. Jardines del Sol, CP. 45050, Zapopan, Jalisco, Mexico

    Bulgaria Office

    49 Bacho Kiro Street, Sofia, 1000, Bulgaria

    Canada Office​

    895 Don Mills Road, Two Morneau Shepell Centre, Suite 900, Toronto, Ontario, M3C 1W3, Canada

    UK Office

    Export House, Cawsey Way, Woking Surrey, GU21 6QX

    Tel: +44 (0) 14 8361 6611

    UAE Office

    Dubai, UAE – Dubai Internet City, 1st Floor, Building Number 12, Premises ED 29, Dubai, UAE

    Tel: +971-55-6540154
    Tel: +971-04-2505173

    Pakistan Office

    163 Bangalore Town, Main Shahrah-e-Faisal, Karachi –
    75350

    705, Business Center, PECHS Block-6, Shahrah-e-Faisal,
    Karachi – 75350

    First Floor, Blue Mall 8-R, MM Alam Road Gulberg III, Lahore

    Tel: +92-21-3432 3721-4 

    © 2021, Folio3 Software Inc., All rights reserved.

    • Privacy policy and terms of use
    • Cookie Policy
    Follow us on
    Facebook-f
    Twitter
    Linkedin-in

    Get a free app audit

      Tired of your app not performing up to the mark?

      Get a free technology and app strategy review.