Using Android Assets Directly.

Do you know the assets placed inside the res directory can be directly accessed and used in your android application. The res directory contains structured values which predefined semantics for the Android platform. In Android the assets directory can be used to store any kind of data. Developer can access files stored in this folder based on their path. The assets directory can also have sub-folders to arrange things nicely.

Info Tip

Developer could also store unstructured data in the /res/raw folder. But it is considered good practice to use the assets directory for such data.

Now coming to main topic how to access data directly placed inside the asset folder.Well In android apart from accessing the resources based on their Ids, developer can make use of the Asset Manager. Let us take a look at it how it is done.

Accessing and Using Data via Android Asset Manager

You access this data via the AssetsManager which you can access via the getAssets()method from an instance of the Context class.

The AssetsManager class allows you to read a file in the assets folder as InputStream with the open() method. The following code shows an example for this.


 // getting the instance of AssetManager
 AssetManager manager = getAssets();

// read "testimg.png" bitmap from the assets folder
 InputStream ISopen = null;
 try {
       ISopen= manager.open("testimg.png");
        Bitmap bitmap = BitmapFactory.decodeStream(ISopen);
      //assign the bitmap to an ImageView in layout
       ImageView imgview = (ImageView)       
       findViewById(R.id.imgViewHolder);
       imgview.setImageBitmap(bitmap);
 } 
 catch (IOException e) 
  {
    e.printStackTrace();
  } 
  finally 
   {
     if (ISopen != null) {
     try {
          ISopen.close();
          } catch (IOException e) 
            {
              e.printStackTrace();
            }
        }
     }// endof Finallyblock