Android Assets Gen is a Kotlin code generator designed to streamline the management of assets, fonts, JSON files, and other resources in Android applications. The primary goal of this project is to eliminate the reliance on string-based APIs for accessing these resources, which can lead to errors and make code maintenance challenging.
Inspired by SwiftGen & FlutterGen
AndroidGen: Java version
output.mp4
In Android development, accessing resources from the asset folder often involves hardcoding file paths. This practice can create confusion regarding where a particular resource is used, when it is accessed, and what features it impacts. Android Assets Gen addresses these issues by providing a centralized solution for managing asset resources.
- Hardcoded Paths: The project helps developers avoid hardcoding file paths, reducing the risk of typos and errors.
- Resource Management: It offers a structured way to manage asset resources, making it easier to understand and maintain the codebase.
- Type Safety: By generating Kotlin enum classes, the project enhances type safety when accessing assets, ensuring that developers use the correct resource paths.
With Android Assets Gen, developers can focus on building features rather than worrying about the intricacies of resource management. The generated code provides a clear and safe way to access assets, improving overall code quality and maintainability.
The development of Android applications, when using resources from the Asset folder, often involves hardcoding file paths. This becomes quite challenging as it's unclear where a particular resource is used, when it's accessed, and what feature it impacts. Consequently, a centralized place to manage these asset resources is necessary.
I've written a Python script to traverse all files within the asset folder and generate corresponding Kotlin enum classes based on the folder structure. These enum classes will then manage the file paths within the folder.
Using asset path string directly is not safe.
main
└── assets
└── app_resources
├── img_sketch.jpg
├── Inter-Bold.ttf
└── language.json
❌ DO NOT
What would happen if you made a typo?
fun loadImageBad(imageView: ImageView) {
Glide.with(imageView)
.load(Uri.parse("file:///android_asset/app_resources/img_sketch.jpg"))
.into(imageView)
}
fun loadJsonFileBad(asset: AssetManager) : String {
val jsonString = asset.open("lang/language.json")
.bufferedReader()
.use { it.readText() }
return jsonString
}
fun createTypefaceSpanBad(asset: AssetManager) : TypefaceSpan {
val typeface: Typeface =
Typeface.createFromAsset(asset, "fonts/Inter-Bold.ttf")
return CustomTypefaceSpan("", typeface)
}
⭕️ SHOULD
We want to use it safely.
AppResources.kt
file is generated by android_assets_gen.py
fun loadImage(imageView: ImageView) {
Glide.with(imageView)
.load(AppResources.IMG_SKETCH.toUri())
.into(imageView)
}
fun loadJsonFile(asset: AssetManager) : String {
val jsonString = asset.open(AppResources.LANGUAGE.path())
.bufferedReader()
.use { it.readText() }
return jsonString
}
fun createTypefaceSpan(asset: AssetManager) : TypefaceSpan {
val typeface: Typeface =
Typeface.createFromAsset(asset, AppResources.INTER_BOLD.path())
return CustomTypefaceSpan("", typeface)
}
- Download file:
android_assets_gen.py
and save it in Android Root project
<Root Projects>
├── .gradle
├── app
│ └── src
│ ├── androidTest
│ └── main
│ ├── assets
│ │ └── app_resources
│ │ ├── img_sketch.jpg
│ │ ├── Inter-Bold.ttf
│ │ └── language.json
│ ├── java
│ │ └── com.app.demo
│ │ ├── ui.theme
│ │ └── MainActivity.kt
│ ├── res
│ └── AndroidManifest.xml
│ └── test [unitTest]
├── .gitignore
├── build.gradle.kts
├── proguard-rules.pro
├── gradle
│ └── .gitignore
├── android_assets_gen.py <---------------
├── build.gradle.kts
├── gradle.properties
├── gradlew
├── gradlew.bat
├── local.properties
├── settings.gradle.kts
├── External Libraries
└── Scratches and Consoles
- Run terminal, case input:
python3 android_assets_gen.py
Enter the package name: com.app.demo
- Run terminal, case command line:
python3 android_assets_gen.py com.app.demo
/// GENERATED CODE - DO NOT MODIFY BY HAND
/// *****************************************************
/// Android assets gen file
/// Generated by android_assets_gen.py
/// *****************************************************
package com.app.demo.gen
import android.net.Uri
enum class AppResources(val fileName: String) {
IMG_SKETCH("img_sketch.jpg"),
LANGUAGE("language.json"),
INTER_BOLD("Inter-Bold.ttf")
}
fun AppResources.path() = "app_resources/${this.fileName}"
fun AppResources.toUri(): Uri = Uri.parse("file:///android_asset/${path()}")
Android Assets Gen is a Kotlin code generator designed to streamline the management of asset resources in Android applications. It eliminates the need for hardcoded string paths, making your code safer and easier to maintain.
Using Android Assets Gen helps prevent errors associated with hardcoded file paths, such as typos or incorrect references. It provides a centralized way to manage asset resources, improving code readability and maintainability.
To install Android Assets Gen, download the android_assets_gen.py
script and place it in the root directory of your Android project. Follow the usage instructions in the usage.md
file to set it up.
Yes, while the generated Kotlin classes are designed to be used as-is, you can modify them after generation if you need to add custom functionality. However, be cautious not to alter the structure that the generator relies on.
Android Assets Gen can manage various types of assets, including images, fonts, and JSON files. As long as the assets are located in the assets
folder of your Android project, they can be processed by the generator.
If you encounter an error, check the console output for any error messages. Common issues include incorrect folder paths or missing permissions. Ensure that the assets
folder exists and contains the files you want to manage.
Yes, you can run the android_assets_gen.py
script again at any time to regenerate the Kotlin classes. This will update the classes based on any changes made to the assets in the assets
folder.