3

I'm trying to load my vertices array from assets/model.txt I have OpenGLActivity, GLRenderer and Mymodel classes i added this line to the OpenGLActivity:

public static Context context;

And this to Mymodel class:

Context context = OpenGLActivity.context;
    AssetManager am = context.getResources().getAssets();
    InputStream is = null;
    try {
        is = am.open("model.txt");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Scanner s = new Scanner(is);
    long numfloats = s.nextLong();
    float[] vertices = new float[(int) numfloats];
    for (int ctr = 0; ctr < vertices.length; ctr++) {
        vertices[ctr] = s.nextFloat();
    }

But it does'n work (

genpfault
  • 51,148
  • 11
  • 85
  • 139
user1092140
  • 33
  • 1
  • 3

1 Answers1

6

I have found in Android it is very important with Activities (and most other classes) not to have references to them in static variables. I try to avoid them at all costs, they love causing memory leaks. But there is one exception, a reference to the application object, which is of course a Context. Holding a reference in a static to this will never leak memory.

So what I do if I really need to have a global context for resources is to extend the Application object and add a static get function for the context.

In the manifest do....
<application    android:name="MyApplicationClass" ...your other bits....>

And in Java....

public class MyApplicationClass extends Application
{
   private Context appContext;

    @Override
    public void onCreate()
    {//Always called before anything else in the app
     //so in the rest of your code safe to call MyApplicationClass.getContext();
         super.onCreate();
         appContext = this;
    }

    public static Context getContext()
    {
         return appContext;
    }
}
David Manpearl
  • 12,362
  • 8
  • 55
  • 72