fragment中this.getActivity出现空指针异常

首先,因为fragment容易被销毁,所以在应用中利用this.getActivity()获取fragment所附着的Activity时会出现空指针异常的问题。这里的空是因为fragment被销毁,this为null而不是Activity为null.
解决方法:在应用程序级的类即继承自Application类中添加如下代码

public class MyApplication extends Application{
    ...
   private static MyApplication mContext;
   @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        mContext = this; //初始化mContext
        
     }
     /**
     * 获取context
     * @return
     */
    public static Context getInstance()
    {
        if(mContext == null)
        {
            mContext = new MyApplication();
        }
        return mContext;
    }
}

在fragment中直接通过调用MyApplication.getInstance()就可以获得应用程序级上下文。解决了调用this.getActivity()引起的空指针异常的问题。
以上基于借鉴其他大神的代码的基础上所得。

你可能感兴趣的:(fragment中this.getActivity出现空指针异常)