应用程序子类类返回空指针异常

时间:2013-09-26 11:49:32

标签: android caching application-singleton

我正在创建一个应用程序,我需要从服务器加载所有组件的图像,如按钮,徽标..我使用了三个类MemoryCache,FileCache和ImageLoder类来自fedors Lazylist的例子 https://github.com/thest1/LazyList/tree/master/src/com/fedorvlasov/lazylist 我们可以将url和View传递给ImageLoader并加载,缓存图像等。

所以我想在整个应用程序中初始化ImageLoder类并在其他活动中重复使用它,为了做到这一点,我在我的MyGlobalClass中为它创建了一个对象,并使用像这样的应用程序。

public class MyGlobalClass extends Application {
    private static Context context;
    private static MyGlobalClass singleton;
    private static ImageLoader imageLoder = new ImageLoader(getAppContext());
    private static String[] urls;

    public MyGlobalClass getInstance() {
        return singleton;
    }

    public void onCreate() {
        super.onCreate();
        singleton = this;
        MyGlobalClass .context = getApplicationContext();

        urls = getResources().getStringArray(R.array.urls);
    }

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

    public ImageLoader getImageLoader() {
        return imageLoder;
    }

    public String[] getUrls() {
        return urls;
    }
}

我在 AndroidManifest.xml 中创建了<appplication>字段为

<application
    android:name="com.xx.yy.MyGlobalClass"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher">
</application>

但是当我在其他活动中使用它时,比如创建全局类的对象我正在这样做:

MyGlobalClass myGClass = (MyGlobalClass)getApplicationContext(); // null pointer here

它返回一个空指针异常。

我想在ImageLoader中访问HomeActivity,如下所示:

ImageButton homeBt = (ImageButton) findViewById(R.id.imageButton2);
ImageLoader imgLoader=(ImageLoader)myGClass.getImageLoader();
String[] urls=myGClass.getUrls();
imgLoader.DisplayImage(urls[1], cameraBt);

有人能看到我的代码有什么问题并建议怎么做吗?我还创建了一个单例字段,但不知道为什么,以及如何使用它。请提供一些例子。 我实际上是在onCreate()之前在activity类中添加了上面的异常行,所以可能是问题..但是当我在HomeActivity中的onCreate()中添加它时,它会给我类强制转换异常...无法强制转换为android。 app.Application to com.xx.yy.MyGlobalClass

1 个答案:

答案 0 :(得分:1)

实际上iam在AndroidManifest.xml文件中不知不觉地创建了另一个“应用程序”标签,事实是--android:name =“com.xx.yy.MyGlobalClass” - 应该添加到同一个“应用程序”标签中之前创建,如果有的话 在关于ClassCastException问题的答案中,每个人都提到我们需要在ManifestFile中添加带有“android:name”属性的标签..但是没有指明它在哪里..,我必须学习它几乎一半的时间浪费,  希望对别人有所帮助。谢谢syed

相关问题