Table of contents |
|
Assets Folder in Android Studio |
|
But when to use which folder? |
|
Images |
|
Understanding File Handling in Android |
|
Accessing Files in Android |
|
How to Create Assets Folder in Android Studio? |
|
Android Studio differs from Eclipse ADT by not having an Assets folder. In Eclipse ADT, the Assets folder is used to store web files like HTML. Assets in Android Studio allow the inclusion of various files such as text, XML, HTML, fonts, music, and videos in the application. Using Assets is essential when you need to access raw data as opposed to resources treated by Android's resource system.
The question arises: why use the Assets folder instead of a Resource Raw Folder? Let's explore the differences between the two.
In Android, raw asset files like JSON, text, mp3, HTML, and PDF can be stored in two locations:
Both locations seem similar as they allow reading files and generating InputStream. For assets:
// From assets
assets.open(assetPathFilename)
// From res/raw
resources.openRawResource(resourceRawFilename)
resources.openRawResource(R.raw.filename)
Placing a file in res/raw ensures correct file-naming during compile time checks.
In assets, filenames can be dynamically accessed and listed during runtime, while in res/raw, filenames must be known and coded in advance.
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 |
Putting files in the res/raw folder simplifies file access in XML files. For instance, to access a file in XML, it should be placed in the res/raw folder. Let's understand this with an example:
Example: If you have an audio file that your app needs to access, you can place it in the res/raw folder and easily reference it in your XML layout files.
Creating an assets folder in Android Studio is essential for storing raw files that your app may need. Below are the detailed steps to create an assets folder in Android Studio:
Switch your project to Android mode to begin the process.
Navigate to app > right-click > New > Folder > Asset Folder to create the asset folder.
When prompted, keep all settings default. Ensure 'main' is selected under the target source set, then click finish.
Within the app folder, you'll find the newly created assets folder named "assets".
Engage with the content by logging in and sharing your thoughts!