Create Assets Folder, Add Files and Read Data From It

Sometimes, we need to read the data stored in the files during runtime and want to make sure the data is not tampered by the Android build system. In this article, we will take a look at how to create the assets folder using Android Studio and read the stored data from it.

First, Right-click on the module name or the package name. This opens an option window where we need to select the Assets Folder option by hovering over New and then on the Folder option.

Create Assets Folder Android

Now, we will see a window where we change the folder location and the source set. Change the values if necessary otherwise keep the defaults and click Finish. It may trigger a Gradle Sync.

Configure Assets Folder Android

Irrespective of the sync, the Assets folder is created and is visible in the module. Now, Right-click on the Assets folder and click on the File option by hovering over the New option.

Create Assets File Android

Enter the name of the file name and click Enter to create the file.

Enter File Name Android

The file with the name user_details.json is created under the assets folder. Add some JSON data to the file so that we can read it.

AAPT2 doesn't generate resource ids for the files stored in the assets folder, which means we cannot reference the files directly in the code or in the XML. This is the main reason why we need to use AssetManger to read the assets.
// Read the file as stream using the Asset Manager
val inputStream = context?.assets?.open("user_details.json")
// Read the input stream as a text using the Reader
val jsonString = inputStream?.bufferedReader().use { it?.readText() }
if (DBG) Log.d(TAG, "Json String: $jsonString")
Data from the JSON file is printed to the Logcat. We can convert the String to an Object manually or using libraries like GSON.

Popular posts from this blog

How to Read Metadata from AndriodManifest File

Change Snackbar Position When Bottom App Bar or Bottom Navigation View Is Present

How to Change Material Chip Text Size, Text Style and Font

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Add Options Menu to Activity and Fragment