繁体   English   中英

无法从静态方法Android访问任何静态方法:ContextWrapper类型的getResources()

[英]Cannot access none static methods from static method, Android: getResources() from the type ContextWrapper

我有一个静态类,其中包含叠加层项目,这些叠加层项目由主类调用,然后添加到叠加层本身。

我可以使它在没有图像类型的情况下工作,但是我想使用它们,但是当我出现以下错误时:无法从ContextWrapper类型对非静态方法getResources()进行静态引用

通过遵循我尝试添加的一些指南,我已经尝试了很多方法来克服此问题:

     private static Context context;

    public void onCreate(){
        super.onCreate();
        Mine.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return Mine.context;
    }

我还确保将清单中的类作为应用程序使用。

该类如下:

    public static ArrayList<ExtendedOverlayItem> array = new ArrayList<ExtendedOverlayItem>();

public ArrayList<ExtendedOverlayItem> getMine() {
    return array;
}



public static  void addMe() {
    Drawable myDrawable = getResources().getDrawable(R.drawable.draw);  //This is the line that doesn't work
    ExtendedOverlayItem myMarker1 = new ExtendedOverlayItem(
            "sample", "sample", new GeoPoint(85.123456,
                    -14.123456), null);
    myMarker1.setMarker(myDrawable);

    myMarker1.setDescription("This is a test description");
    array.add(myMarker1);
}

 private static Context context;

    public void onCreate(){
        super.onCreate();
        Mine.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return Mine.context;
    }

我尝试添加以下内容:

myMarker1.setMarker(Mine.getAppContext().getResources().getDrawable(R.drawable.example));

但是从main方法调用时,我仍然会遇到空指针错误。如果我将图像遗漏在外,则可以正确调用它。

在main方法中,我按如下方式调用此类:

Mine.addMe();
ItemizedOverlayWithBubble<ExtendedOverlayItem> thisThing = new   ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, Mine.array, map);
map.getOverlays().add(thisThing);

任何建议,不胜感激。

在Java中,静态方法不能访问任何非静态方法或变量。

One of the basic rules of working with static methods is that you can't access a nonstatic method or field from a static method because the static method doesn't have an instance of the class to use to reference instance methods or fields.

有关更多信息, 文档

这是如何访问它们的好例子

如果在此行之前设置了上下文

Drawable myDrawable = getResources().getDrawable(R.drawable.draw);

然后使用

Drawable myDrawable = context.getResources().getDrawable(R.drawable.draw);

因为添加我是静态方法,无法获取getResources()上下文

编辑:

getResources()在上下文上调用。 并且在您的代码中,您是从静态方法调用它的,但是静态方法无法访问应用程序上下文的非静态方法。 因此您为上下文创建了一个静态对象并将上下文存储在其中。 但是您是否在调用上述行之前检查设置的上下文是否不为null并设置了?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM