getActivity()在Fragment中返回null

时间:2013-11-01 04:40:44

标签: android fragment

当我改变方向并滑动时,它会崩溃。 这是我的日志猫

11-01 11:21:19.715: E/AndroidRuntime(4336): FATAL EXCEPTION: main 
11-01 11:21:19.715: E/AndroidRuntime(4336): java.lang.NullPointerException
11-01 11:21:19.715: E/AndroidRuntime(4336):     at com.example.saisuke.CalendarAdapter.<init>(CalendarAdapter.java:33)
11-01 11:21:19.715: E/AndroidRuntime(4336):     at com.example.saisuke.MonthFragment.updateCurrentMonth(MonthFragment.java:161) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at com.example.saisuke.MonthFragment.onNextMonth(MonthFragment.java:177)
11-01 11:21:19.715: E/AndroidRuntime(4336):     at com.example.saisuke.Saisuke$1.onPageScrollStateChanged(Saisuke.java:107) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at android.support.v4.view.ViewPager.setScrollState(ViewPager.java:398)
11-01 11:21:19.715: E/AndroidRuntime(4336):     at android.support.v4.view.ViewPager.access$000(ViewPager.java:84) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at android.support.v4.view.ViewPager$3.run(ViewPager.java:243) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
11-01 11:21:19.715: E/AndroidRuntime(4336):     at android.view.Choreographer.doCallbacks(Choreographer.java:555) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at android.view.Choreographer.doFrame(Choreographer.java:524)
11-01 11:21:19.715: E/AndroidRuntime(4336):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
11-01 11:21:19.715: E/AndroidRuntime(4336):     at android.os.Handler.handleCallback(Handler.java:615) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at android.os.Handler.dispatchMessage(Handler.java:92) 11-01 
11:21:19.715: E/AndroidRuntime(4336):   at android.os.Looper.loop(Looper.java:137)
11-01 11:21:19.715: E/AndroidRuntime(4336):     at android.app.ActivityThread.main(ActivityThread.java:4898) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at java.lang.reflect.Method.invokeNative(Native Method) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at java.lang.reflect.Method.invoke(Method.java:511) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 
11-01 11:21:19.715: E/AndroidRuntime(4336):     at dalvik.system.NativeStart.main(Native Method)

MainActivity.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saisuke);
        ((Global) this.getApplication()).setStraightMode(false);
        mOldState = ((Global) this.getApplication()).getStraightMode();
        monthList = new ArrayList<MonthFragment>(3);
        curMonth = Calendar.getInstance();
        Calendar prevMonth, nextMonth;
        prevMonth = (Calendar) curMonth.clone();
        nextMonth = (Calendar) curMonth.clone();
        prevMonth.set(Calendar.MONTH, prevMonth.get(Calendar.MONTH) - 1);
        nextMonth.set(Calendar.MONTH, nextMonth.get(Calendar.MONTH) + 1);
            monthList.add(MonthFragment.newInstance(prevMonth));
            monthList.add(MonthFragment.newInstance(curMonth));
            monthList.add(MonthFragment.newInstance(nextMonth));
        //tmpCurMonth = monthList[1].getCurCalendar();
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), monthList);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub
                if (arg0 == ViewPager.SCROLL_STATE_IDLE) {
                    if (mSelectedPageIndex < PAGE_MIDDLE) {
                        monthList.get(0).onPreviousMonth();
                        monthList.get(1).onPreviousMonth();
                        monthList.get(2).onPreviousMonth();  
                    } else if (mSelectedPageIndex > PAGE_MIDDLE) {
                        monthList.get(0).onNextMonth();
                        monthList.get(1).onNextMonth();
                        monthList.get(2).onNextMonth();
                    }
                    mViewPager.setCurrentItem(1, false);
                    //tmpCurMonth = monthList[1].getCurCalendar();
                    mSectionsPagerAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub
                if (((Global) getApplication()).getStraightMode() != mOldState){
                    mOldState = ((Global) getApplication()).getStraightMode();
                    mSectionsPagerAdapter.notifyDataSetChanged();   
                }
            }

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                mSelectedPageIndex = arg0;
            }
        });
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setCurrentItem(1, false);
    }

MyFragent.java

static MonthFragment newInstance(Calendar a) {
        MonthFragment f = new MonthFragment(a);
        return f;    
    }

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        if (savedInstanceState != null) {
            // Restore last state
            calendar = (Calendar) savedInstanceState.getSerializable("starttime");
        }

        mMainView = inflater.inflate(R.layout.fragment_saisuke, container, false);
        adap = new CalendarAdapter(getActivity(), calendar);
        ....        
        return mMainView;
    }

protected void updateCurrentMonth() {
        adap.updateData();
    }

protected final void onNextMonth() {
        if (calendar.get(Calendar.MONTH) == Calendar.DECEMBER) {
            calendar.set((calendar.get(Calendar.YEAR) + 1), Calendar.JANUARY, 1);
        } else {
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
        }
        updateCurrentMonth();
    }

2 个答案:

答案 0 :(得分:5)

你自己的解决方案非常不推荐,你永远不应该跳过生命周期方法中对super()的调用。

相反,找出问题所在。

提示:

  1. 覆盖(并调用Super!)每个Activity / Fragment生命周期方法。 OnCreate,OnResume,OnPause,OnStop,OnCreateView,OnViewCreated等等......

  2. 为每个添加LOG行并运行您的应用。查看哪些被调用以及按哪种顺序。

  3. 旋转您的设备。比较结果。

  4. 找出您的成员变量未初始化的原因,因为在轮换时,活动被销毁并重新创建。

  5. 对于不使用非常糟糕的黑客行为以及您的Android应用程序不会神秘崩溃这一事实感到高兴。

答案 1 :(得分:-4)

我终于找到了如何解决我的错误 这很简单。我只需要覆盖活动中的 onSaveInstanceState 函数并省略 super.onSaveInstanceState(outState); 它看起来像那样

@Override
protected void onSaveInstanceState(final Bundle outState) {         
    //super.onSaveInstanceState(outState);
}