0

我有一个包含覆盖项目的静态类,由我的主类调用,然后添加到覆盖本身。

我可以在没有图像类型的情况下使其工作,但我想使用它们,但是当我这样做时,出现以下错误:无法从类型 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);

非常感谢任何建议。

4

2 回答 2

0

在 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.

更多信息文档

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

于 2013-08-22T12:46:50.670 回答
0

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

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

然后使用

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

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

编辑:

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

于 2013-08-22T12:57:57.890 回答