Several users are bilingual, so they may require certain apps to be in different languages. For example, you might be able to communicate in both English and French, with French being your native language. On your device, you might have set your system’s default language to English. The majority of apps can use this well, while some, like financial ones, would be far better in French since it’s more comfortable.
In my case, I am trying to learn a new foreign language. Changing the app language has allowed me to access some apps for brief periods of time while keeping my system’s default language set to English. This has helped me become more familiar with the language, encouraging me to use it in order to navigate the app.
Whatever your case may be, using this feature will allow you to fine-tune your experience to ideally fit you (and the user of your app), no matter what language or combination you choose.
Navigate to your System settings: Settings > System > Languages & Input > App Languages. Select an app and then choose a specific language for it. Or you can navigate to your Apps settings: Settings > Apps. Select an app, then under Language you can also choose a specific language for it.

If your app supports different languages, you’re ready to implement this feature. Otherwise, look into localizing your Android app first, because adding per-app language settings to your app doesn’t translate your app’s resources automatically.
Implementing this feature in your app requires 3 simple steps:
Create a file called res/xml/locales_config.xml. This sample file will help you construct yours. Make sure to only have your localized languages specified there. Otherwise selecting a language that’s not supported by your app will fall back to the default language, which is the locale specified in res/values/strings.xml
In the manifest, add a line that points to this new file as follows:
Use the resourceConfiguration property in your app’s module-level build.gradle file to specify the same languages. As long as the resourceConfigurations property is present, the build system will only include these specified languages in the APK, avoiding the inclusion of translated strings from libraries that may support languages other than the ones your app supports.
To test how this feature looks on your app: navigate to your app’s info, find the Language section, change the Language of your app and check if it shows the correct language.
If this post was of any help to you, or if you’d like me to write about any specific Android related topics, let me know! Drop me a DM on Twitter @yalematta ✌🏼
]]>While both Preferences and Proto DataStore allow saving data, they do this in different ways. One important feature is applied only when using Proto DataStore, and it is Type Safety.
With Proto DataStore we don’t have to use keys. Instead we define a schema using Protocol Buffers. And with Protocol Buffers we can persist strongly typed data.
One of the downsides of SharedPreferences and Preferences DataStore is that there is no way to ensure that keys are accessed with the correct type. Using Proto DataStore, we know what types are stored and we will just provide them.
Protocol Buffers were developed by Google for storing and interchanging all kinds of structured information. They are used for serializing structured data. It is similar to XML and other similar data formats, but it’s smaller, faster and simpler.
If you don’t know what serialization is, it’s the process of translating a data structure or object state into a format that can be stored, like for example, a file or a memory data buffer.
We need to define how we want our data to be structured once, and the compiler will generate the source code for us to easily read and write the structured data.
That said, with Proto Datastore we will serialize and save our custom data structure using Protocol Buffers and of course deserialize and read the values whenever we need to.
In this simple project, we are implementing the same Remember Me functionality as in the previous post. We are currently using SharedPreferences to store this value and redirect the user to the Welcome screen once it’s checked. We will migrate the code to use Proto DataStore.

To get your hands on the code, consider checking this GitHub repo.
The final code is located in the proto_datastore branch.
In order to use Proto Datastore we will need to define our Protobuf schema in a new .proto file. So instead of creating a model class in Kotlin, we will define it in a Protobuf schema instead. And there’s a new syntax that we need to follow when writing this schema.
We will install a plugin in Android Studio called Protocol Buffer Editor that will help us write the Proto file. Make sure to install it before creating your proto files.

Once installed, we switch to our Project View and under app/src/main we create a new directory called proto. Inside this directory we create a new file user_prefs.proto where we define our Protocol Buffer schema as follows:
Let me walk you through this syntax:
There are 2 versions for the Protobuff syntax: proto2 and proto3. You can check the documention for more info regarding these two different versions. In our case, we are going to use proto3.
Then, we are going to write 2 options:
First, our java_package name. We need it in order to tell our compiler where to generate our classes from this protocol buffer.
The second option is java_multiple_files. We will set it to true and this means that we need to create a separate file for each top level message object of this proto file.
The message keyword defines the data structure. And inside it, we define the members of this structure. As you may have noticed we have different primitive types in this syntax.

By taking a look at the documentation, we can learn that: int32 in Java represents an Integer, int64 a Long and bool is a Boolean.
We create an object UserPreferences with 2 member fields: a bool, a string and an int32. Don’t be confused when you see these 1, 2 and 3. These are not actual values but unique numbers to identify our fields in the message binary format and they should not be changed once our message object is in use.
Before we continue let’s place this plugin at the top of our build.gradle file.
Then we need to add two dependencies, one for Protobuf and one for Proto DataStore.
And finally at the end of our build.gradle file we configure Protobuf and we sync our project.
Now that we have added this plugin, we should be able to see the automatically generated files by this plugin from our user_prefs.proto file.
Rebuild the project to see those files inside the java (generated) folder.
We find a new UserPrefs folder that represents our proto file, and a UserPreferences class that represents our message object. Inside it we have java code that implements some getters and setters for this UserPreferences message object.
To tell DataStore how to read and write the data type we defined in the proto file, we need to implement a Serializer. The Serializer defines also the default value to be returned if there’s no data saved yet.
Back in our project, we create a class called UserPreferencesSerializer which extends Serializer
Next we create our Repository which we call UserPreferencesRepository.
We create a new variable called userPreferencesFlow of type Flow
We create the suspend updateUsername function which will update one field from our UserPreferences member values. We will call preference.toBuilder(). and we choose the setter method that we need from our generated class.
P.S: Don’t forget to create a method to update each field.
To clear data, we can either clear the preferences all together or clear a specific preference by its method from our generated class.
In our LoginViewModel, we create a variable for our UserPreferences, read its data from our DataStore as a Flow and then convert it to LiveData.
Next we create a new function named saveUserPreferences and we pass to it the values that we want to update. We call viewModel scope and run the following code inside a coroutine since our update functions in our Repository are using Kotlin Coroutines.
LoginViewModelFactory is a ViewModelProvider.Factory that is responsible to create our instance of LoginViewModel later in our Activity. We will pass to it the DataStoreRepository which is need in LoginViewModel’s constructor.
In our Activity, we first create our userPreferencesDataStore and we initialize it and pass to it a file name as well as our Serializer class.
If we are migrating our existing data from the SharedPreferences, when creating our DataStore, we should add a migration based on the SharedPreferences name.
And when creating the dataStore we need to update the DataStore builder and assign to the migrations parameter a new list that contains an instance of our SharedPreferencesMigration.
Define the mapping logic from SharedPreferences to UserPreferences inside your SharedPreferencesMigration.
DataStore will be able to migrate from SharedPreferences to DataStore automatically, for us.
Inside our onCreate function, we initialize our ViewModel and we observe our fields’ values, so that whenever this data changes we will update it in its corresponding text field.
And whenever we click our login button, we store the value from our editText and checkBox field and update it in our DataStore using the saveUserPreferences function.
Now that we migrated to Preferences DataStore let’s recap!
DataStore:
DataStore has 2 different implementations: Preferences DataStore and Proto DataStore.
Proto DataStore:
If this post was of any help to you, or if you’d like me to write about any specific Android related topics, let me know! Drop me a DM on Twitter @yalematta ✌🏼
]]>So if you’re currently using SharedPreferences, consider migrating to DataStore instead. And good news, it’s now in Beta 🎉
Jetpack DataStore is a data storage solution that provides two different implementations: Preferences DataStore and Proto DataStore.
Preferences DataStore stores and accesses data using keys.
Proto DataStore stores data as instances of a custom data type and requires creating a schema using protocol buffers.
DataStore uses Kotlin coroutines and Flow to store data asynchronously, consistently, and transactionally unlike SharedPreferences.
In this article, we will focus on Preferences DataStore.
In this simple project, we are implementing the Remember Me functionality of a Login screen. We are currently using SharedPreferences to store this value and redirect the user to the Welcome screen once it’s checked. We will migrate the code to use DataStore.

To get your hands on the code, consider checking this GitHub repo.
The final code is located in the preferences_datastore branch.
The biggest downsides of SharedPreferences include:
Luckily Jetpack DataStore addresses those issues. Since it’s powered by Flow, DataStore saves the preferences in a file and performs all data operations on Dispatchers.IO under the hood. And your app won’t be freezing while storing data.
First, add the Preference DataStore dependency in the build.gradle file:
We have also added the Lifecycle dependencies for using ViewModel:
Inside a new package called repository, create the Kotlin class DataStoreRepository.kt. In this class we are going to store all the logic necessary for writing and reading DataStore preferences. We will pass to it a dataStore of type DataStore<Preferences> as a parameter.
Let’s create a data class called UserPreferecences. It will contain the two values we’re going to save.
Unlike SharedPreferences, in DataStore we cannot add a key simply as a String. Instead we have to create a Preferences.Key<String> object or simply by using the extension function stringPreferencesKey as follows:
In order to save to DataStore, we use the dataStore.edit method using the keys we created above.
You may have noticed that we’re using a suspend function here. This is because dataStore.edit uses Coroutines. This function accepts a transform block of code that allows us to transactionally update the state in DataStore. It can also throw an IOException if an error was encountered while reading or writing to disk.
To read our data, we will retrieve it using dataStore.data as a Flow<UserPreferences>.
Later, we are going to convert this Flow emitted value to LiveData in our ViewModel.
Make sure to handle the IOExceptions, that are thrown when an error occurs while reading data. Do this by using catch() before map() and emitting emptyPreferences().
To clear data, we can either clear the preferences all together or clear a specific preference by its key.
In another viewmodel package, create the LoginViewModel class.
We’re retrieving userPreferences and converting the Flow into LiveData in order to observe it in our Activity. And since saveToDataStore and clearDataStore are suspended functions, we need to run them from inside a coroutine scope, which is the viewmodel scope in this case.
LoginViewModelFactory is a ViewModelProvider.Factory that is responsible to create our instance of LoginViewModel later in our Activity. We will pass to it the DataStoreRepository which is need in LoginViewModel’s constructor.
If we are migrating our existing data from the SharedPreferences, when creating our DataStore, we should add a migration based on the SharedPreferences name. DataStore will be able to migrate from SharedPreferences to DataStore automatically, for us.
In our activity, we first observe our userPreferences as liveData from our ViewModel.
Whenever Remember Me is observed as checked, we redirect the user to the Welcome screen. Whenever we click the login button, if our checkbox is checked we update our userPreferences, otherwise we clear our saved user preferences.
For the simplicity of our application, we will use the same ViewModel in our WelcomeActivity as well. We observe the username and display it whenever it is not empty. And once we log out we clear our saved userPreferences.
Now that we migrated to Preferences DataStore let’s recap!
DataStore:
Join me in the next post to learn how to use Proto DataStore.
If this post was of any help to you, or if you think it requires further explanation, I’d love to know! Drop me a DM on Twitter @yalematta ✌🏼
These are free online training courses developed by Google that help you learn how to build basic Android apps. The courses are made up of units. And units are composed of pathways. You may be wondering, what is a pathway? It’s an ordered sequence of activities to learn a specific skill.
An activity can be a video, hands-on coding tutorial (known as a codelab), an article, or quiz. All these activities are meant to help you reach specific learning objectives by the end of each pathway.
This course is also developed by Google, and has ten pathways available. This track requires you to have prior programming experience.
You will learn about:
As you get into more advanced features, you will likely need to learn more programming concepts. You can check out this resource for that.
This is an official set of small and simple annotated examples designed for those new to Kotlin by the Jetbrains team. No prior knowledge of any programming language is required.
This is a series of exercises to get you familiar with the Kotlin syntax and language features. Each exercise is created as a failing unit test, and you need to make it pass.
This course is built in collaboration with Google, but it is not free. It will prepare you to become a professional Android developer and allow you to create a diverse portfolio of projects to show employers.
By the end of this program, you will be able to use Android development platform best-practices, Android Jetpack, and Kotlin to build your own Android apps.
All of Ray Wenderlich’s tutorials are created by a community of mobile development experts from around the world. No matter how long you’ve been coding, their courses format will help you become a better developer!
Some of these courses are free, but some others will require you to have a monthly subscription on their platform to be able to access them.