My Android Launcher Activity的静态引用变为null

时间:2015-03-25 04:48:22

标签: android

在我的Android应用程序中,我将Launcher活动(称为MainActivity)存储在MainActivity类中的静态变量中; 我正在使用这个静态Activity引用来获取应用程序资源,首选项和其他内容;

但有时,我发现应用程序崩溃了,因为对象引用为null;

  1. 是否有任何原因导致对象引用变为NULL?
  2. 如何防止这种NullPointerException?
  3. 我的代码:

    MainActivity:

    public class MainActivity extends Activity {
        private static MainActivity sInstance = null;
    
        public static MainActivity getInstance() {
            return sInstance;
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           sInstance = this;
           // other code
       }
    } 
    

    Helper.java

    public static int getColor(int resID) {
        return MainActivity.getInstance().getColor(resID);
    }
    

1 个答案:

答案 0 :(得分:1)

//For this type of issue, please use application class object. If you used Activity class then when //activity destroys then it will become null. So you got the null pointer exception.


public class MyApplication extends Application {
    public static MyApplication myApplication = null;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        myApplication = (MyApplication) getApplicationContext();
    }

    public static MyApplication getInstance() {
        return myApplication;
    }

}

//Your method looks like this
public static int getColor(int resID) {
        return MyApplication.getInstance().getResources().getColor(resID);
    }