April 28, 2016

While making an applications we use to put our images in the drawable folder. However, many times we have seen developers putting their images in the assets folder. So, the question is which one is faster, or which one is best for the app.

The res directories are accessible from the R.class, and on the other hand assets behaves like a file system. Putting the images in the res folder is having many advantages, like since it is directly accessible from the R.class file it is faster. We can have images of different sizes in the res folder but not in the assets folder. So why there is the assets folder. If we want to compute the asset we want to use at run time, it’s pretty easy. With resources, we would have to declare a list of all the resource IDs that might be used and compute an index into the the list.

One usage of the assets folder is that, when in an app there is a requirement to use Custom font, then that particular font typeface is to be put in the assets folder.

One major difference is resources defined in a library project are automatically imported to application projects that depend on the library. For assets, that doesn’t happen; asset files must be present in the assets directory of the application project(s). However with the introduction of the Android Studio this is no longer required, all because of its gradle File System. Asset directories for library projects are packaged into the .aar files, so assets defined in library projects are merged into application projects (so they do not have to be present in the application’s /assets directory if they are in a referenced library).

Referring image in the res/drawable folder

In xml:


In Java :

ImageView = _imageView;
_imageView = (ImageView) findViewById(R.id.image);

Referring image from the assets folder

ImageView i;
Bitmap bm = getImage("image1.png");
i = (ImageView)findViewById(R.id.image);

then call the method, getImage()

private Bitmap getImage(String strName) throws IOException
    AssetManager assetManager = getAssets();
    InputStream istr = assetManager.open(strName);
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    return bitmap;