来自非Activity类的android getResources()

来自非Activity类的android getResources(),第1张

概述我正在尝试从assets/model.txt加载我的顶点数组我有OpenGLActivity,GLRenderer和Mymodel类我将此行添加到OpenGLActivity:publicstaticContextcontext;这到Mymodel类:Contextcontext=OpenGLActivity.context;AssetManageram=context.getResources().getAssets

我正在尝试从assets / model.txt加载我的顶点数组
我有OpenGLActivity,glrenderer和Mymodel类
我将此行添加到OpenGLActivity:

public static Context context;

这到Mymodel类:

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

但它确实不起作用(

解决方法:

我在AndroID中发现,活动(和大多数其他类)在静态变量中没有引用它们是非常重要的.我试图不惜一切代价避免它们,他们喜欢导致内存泄漏.但是有一个例外,即对应用程序对象的引用,它当然是一个Context.在静态中保持引用将永远不会泄漏内存.

因此,如果我真的需要拥有资源的全局上下文,我所做的就是扩展Application对象并为上下文添加静态get函数.

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

而在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;    }}
总结

以上是内存溢出为你收集整理的来自非Activity类的android getResources()全部内容,希望文章能够帮你解决来自非Activity类的android getResources()所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1109612.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存