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



我正在创建一个应用程序,我需要从服务器加载所有组件(如按钮,徽标(的图像。我正在使用三个类 内存缓存,文件缓存 和 图像洛德类 来自 fedors 懒惰列表示例https://github.com/thest1/LazyList/tree/master/src/com/fedorvlasov/lazylist我们可以将 url 和视图传递给图像加载器并加载、缓存图像等。

所以我想在整个应用程序中只初始化一次 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 中创建了<appplication>字段.xml作为

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

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

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

它返回空指针异常。

我想像这样访问HomeActivity ImageLoader

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

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

>实际上我在不知不觉中在AndroidManifest.xml文件中创建了另一个"应用程序"标签,事实是--android:name="com.xx.yy.MyGlobalClass"--应该添加到您之前创建的同一"应用程序"标签中(如果有的话(,在 ClassCastException 问题的回答中,提到的每个正文都需要在 ManifestFile 中添加带有"android:name"属性的标签。但是没有指定在哪里..,我不得不努力学习它,浪费了将近半天的时间, 希望对其他人有帮助。谢谢赛义德

最新更新