Last Updated: September 29, 2021
·
40.65K
· drdrej

Working with Assets in Android

As you know, Android-App can store some assets inside. For example to package some stuff with PhoneGap, or for your own purpose. You can store their files and load them in your App. If you need this behaviour you maybe should use assets, as provided by Android.

To work with assets in the app-environment you need to use
getContext()-method.

how to load an asset?

In Activity or another Context use the getAssets().open() like in the following example:

try {
     final InputStream in = getContext().getAssets().open( "myFile.xml" );
     ...
} catch(final Throwable tx) {
     ...
}

If file not exists, your App wil throw a FileNotFoundException.

how to list assets?

To list files in the asset-Directory use the list()-method.

Example:

final AssetManager assets = getContext().getAssets();
final String[] names = assets.list( "" );

If you like to list your files in the root-directory of your app, please pass "/" as parameter to the list()-method.

final AssetManager assets = getContext().getAssets();
final String[] names = assets.list( "/" );

how to load assets in a test?

It is important to know, that an Android-Test-App has its own Context. If you write a test, remember that, you have to know wich context you have to use.

Methods to get context:

To get the context of the test-app in your TestCase-Class you need:

  1. use InstrumentationTestCase or ActivityTestCase.

public class MyTest extends ActivityTestCase {
...

}

  1. use getInstrumentation()-method to get the context.

    final Context ctx = getInstrumentation().getContext();

If you like to get the app-context (and not the test-app-context), then you need to use the getTargetContext() (not getContext())

final Context ctx =  getInstrumentation().getTargetContext();

have fun!
Andreas Siebert, 2013