AssetManager in Android

AssetManager in android

Basically, Assets are a raw approach to resource management. We can place any files we want into the assets directory of our project.

If we have a reference to any Context subclass, such as an Activity, we can get a reference to the AssetManager instance provided by the platform:

  1. AssetManager assetManager = getAssets();  

Once we have an AssetManager reference, we can just open a raw InputStream for any asset we put into the assets directory

Like in this way:

  1. <> InputStream input = null;  
  2.   
  3. <> try {  
  4.   
  5. <> input = assetManager.open("mytextfile.txt<> ");  
  6.   
  7. <> } catch (IOException e) {  
  8.   
  9. <> // handle  
  10.   
  11. <> }  

Here is an example as a class having feature of text file reading via AssetManager

For instance

  1. public static class myData  
  2. {  
  3.     public static void loadData(Context context)   
  4.     {  
  5.   
  6.         try   
  7.         {  
  8.             AssetManager am = context.getAssets();  
  9.             InputStream is = am.open("mytextfile.txt");  
  10.             BufferedReader br =  
  11.             new BufferedReader(new InputStreamReader(is));  
  12.             String line = br.readLine();  
  13.             My_Name = line;  
  14.             line = br.readLine();  
  15.             My_Contact = Integer.parseInt(line);  
  16.             br.close();  
  17.         }   
  18.         catch (IOException e)   
  19.         {  
  20.   
  21.             Log.e("Error""Unable to read data from txt file");  
  22.   
  23.         }  
  24.     }  
  25. }