我發現程序啓動時,報如下的NullPointerException異常:
E/AndroidRuntime(4246): Caused by: java.lang.NullPointerException
E/AndroidRuntime(4246): at android.content.ContextWrapper.getResources(ContextWrapper.java:81)
我的源碼如下:
- private OnPageChangeListener mPageChangeListener = new OnPageChangeListener()
- {
- private int bmpW = 0; // 遊標圖片的寬度
- {
- bmpW = BitmapFactory.decodeResource(MainActivity.this.getResources(),
- R.drawable.tab_line_press).getWidth();
- //....
- }
- //...
- }
查看Android源碼(ContextWrapper.java:81),發現是Context的變量mBase爲Null了:
- Context mBase;
- //...
- @Override
- public Resources getResources()
- {
- return mBase.getResources();
- }
於是,發現這個做有問題,在變量的聲明時,Context還沒有傳遞進來呢!
必須等到OnCreate後,才能使用Context去獲取資源(getResources)!