Open In App

Assets Folder in Android Studio

It can be noticed that unlike Eclipse ADT (App Development Tools), Android Studio doesn’t contain an Assets folder in which we usually use to keep the web files like HTML. Assets provide a way to add arbitrary files like text, XML, HTML, fonts, music, and video in the application. If one tries to add these files as “resources“, Android will treat them into its resource system and you will be unable to get the raw data. If one wants to access data untouched, Assets are one way to do it. But the question arises is why in the asset folder? We can do the same things by creating a Resource Raw Folder. So let discuss how the assets folder is different from the Resource Raw folder? 

How the asset folder is different from the Resource Raw folder? 

In Android one can store the raw asset file like JSON, Text, mp3, HTML, pdf, etc in two possible locations:



  1. assets
  2. res/raw folder

Both of them appears to be the same, as they can read the file and generate InputStream as below



// From assets

assets.open(assetPathFilename)

// From res/raw

resources.openRawResource(resourceRawFilename)

But when to use which folder?

Below is some guidance that might be helpful to choose

1. Flexible File Name: (assets is better)

2. Store in subdirectory: (possible in assets)

3. Compile-time checking: (possible in res/raw)

assets.open(“filename”)

resources.openRawResource(R.raw.filename)

So putting a file in the res/raw folder will provide ensure the correct file-name during compile time check.

4. List filenames at runtime: (possible in assets)

assets.list(FOLDER_NAME)?.forEach {  

   println(it)

}

So, in assets, one can read the filename during runtime, list them, and use them dynamically. In res/raw, one needs to code them ready, perhaps in the string resources file.

5. Filename accessible from XML: (possible in res/raw) 

So if you need to access your file in any XML, put it in the res/raw folder. Let’s make a table to remember the whole scenario easily.

Scenario

Assets Folder

Res/Raw Folder
Flexible File Name

YES

NO

Store in subdirectory

YES

NO

Compile-time checking

NO

YES

List filenames at runtime

YES

NO

Filename accessible from XML

NO

YES

How to Create Assets Folder in Android Studio?

Now let’s discuss how to create an assets folder in the android studio. Below is the step-by-step process to create an assets folder in Android studio.

Step 1: To create an asset folder in Android studio open your project in Android mode first as shown in the below image.

Step 2: Go to the app > right-click > New > Folder > Asset Folder and create the asset folder.

Step 3: Android Studio will open a dialog box. Keep all the settings default. Under the target source set, option main should be selected. and click on the finish button.

Step 4: Now open the app folder and you will find the assets folder by the name of “assets” as shown in the below image.


Article Tags :