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

jiahao
  • 3,373
  • 2
  • 35
  • 36
  • Can't you read using FileUtils.readFileToString(new File(Path), Charset.defaultCharset()); – MadLeo Dec 28 '18 at 09: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? – jiahao Jan 08 '19 at 09:41

1 Answers1

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)

vgar
  • 171
  • 6
  • 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? – jiahao Dec 28 '18 at 09:51
  • By passing the context and using AssetManager actually works. Thanks for the answer. – jiahao Dec 28 '18 at 10:21