我正在创建一个应用程序,我需要从服务器加载按钮、徽标等所有组件的图像。我正在使用 Fedors Lazylist 示例 https://github.com/thest1/LazyList/tree/master/src/com/fedorvlasov/lazylist 中的三个类 MemoryCache、FileCache 和 ImageLoder 类,我们可以将 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() 之前的活动类中添加上述异常行,所以这可能是问题所在..但是当我在 HomeActivity 的 onCreate() 中添加它时,它给了我 Class cast Exception..cannot cast to android。 app.Application 到 com.xx.yy.MyGlobalClass