android getResources() from non-Activity class

只愿长相守 提交于 2019-12-06 07:21:16

问题


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 (


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/8463491/android-getresources-from-non-activity-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!