3

Recently I saw it is possible to include assets in the Android Library with the update on November 2018 on the Official documentation here: https://developer.android.com/studio/projects/android-library

But it just describes briefly that "assets" is an optional library that could be included in the Android libraries. It does not cover the way how to access them.

Right now I have a project with several Android libraries. Each library contains a level or it is contained on a level of abstraction. In order to have good isolation, ideally each library should be able to use the code and assets which is contained by its own Android library.

So, my question is, since now we can include assets, in my case a json file, inside of the Android library, is there any way to access those assets directly from the code of the Android library itself, without using the code from the app library?

Storage layer

Thanks in advance P.d.: Here is the source code of my project if anyone is interested: https://github.com/jiahaoliuliu/chutoro/tree/feature/companiesList

2
  • Can't you read using FileUtils.readFileToString(new File(Path), Charset.defaultCharset()); Commented Dec 28, 2018 at 9:33
  • well, that's very brute way to do it. If Android offers you a better way with getAssets, why don't we use it? Commented Jan 8, 2019 at 9:41

1 Answer 1

7

Looks like you want to use the AssetManager.

After importing

import android.content.res.AssetManager; 

and initializing it

AssetManager assetManager = getAssets(); 

you can load assets by using

InputStream input = assetManager.open("PersistentDestinations.json"); 

Please note that you have to convert the InputStream in order to pass it to e.g. a JSONObject. (e.g. see here)

Sign up to request clarification or add additional context in comments.

3 Comments

I am not sure about this, but getAsserts is a method implemented on the ContextWrapper and at least I can access to it from the Android library, I don't think it is possible. Could you provide a more complete answer?
By passing the context and using AssetManager actually works. Thanks for the answer.
This answer DOES NOT cover reading assets that are in an assets folder WITHIN THE LIBRARY.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.