我正在創建一個應用程序,我需要從服務器加載所有組件的圖像,如按鈕,徽標..我使用的三個類的MemoryCache,FileCache從Fedors的ImageLoder類Lazylist例如 https://github.com/thest1/LazyList/tree/master/src/com/fedorvlasov/lazylist 在這裏我們可以通過URL和查看到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;
}
}
我創建<appplication>
領域的AndroidManifest.xml作爲
<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()時,它會給我類轉換異常。無法投射到android .app.Application to com.xx.yy.MyGlobalClass