How can I read files from the asset folder?

Read my previous notes on using Resources

Here is the AssetManager API

How to read my android context variable static method

Search for: How to read my android context variable static method

Here is a link for stackoverflow


Store the application context in your app initialization
  and make it a static variable.
Your application context may be different from Activity context
Use volatile to deal with null values
You can use injection tools like RoboGuice

You will need a context to read the assets


public class MyApplication extends Application
{
   public final static String tag="MyApplication";
   
   //Make sure to check for null for this variable
   public static volatile Context m_appContext = null;

   @Override
   public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
      Log.d(tag,"configuration changed");
   }

   @Override
   public void onCreate() {
      super.onCreate();
      Log.d(tag,"oncreate");
      MyApplication.m_appContext = this.getApplicationContext();
   }

   @Override
   public void onLowMemory() {
      super.onLowMemory();
      Log.d(tag,"onLowMemory");
   }

   @Override
   public void onTerminate() {
      super.onTerminate();
      Log.d(tag,"onTerminate");
   }

}

<application android:name=".MyApplication"
        android:icon="@drawable/icon"

public String getStringFromAssetFile(String filename)
    {
       Context ctx = MyApplication.m_appContext; 
       if ( ctx == null)
       {
          throw new RuntimeException("Sorry your app context is null");
       }
       try
       {
         AssetManager am = ctx.getAssets();
         InputStream is = am.open(filename);
         String s = convertStreamToString(is);
         is.close();
         return s;
       }
       catch (IOException x)
       {
          throw new RuntimeException("Sorry not able to read filename:" + filename,x);
       }
    }
    
    //Optimize later. This may not be an efficient read
    private String convertStreamToString(InputStream is)
    throws IOException
    {   
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       int i = is.read();
       while (i != -1)
       {
          baos.write(i);
          i = is.read();
       }
       return baos.toString();
    }