-1

When I change orientation, and swipe, it crashes. This is my log cat

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();
    }
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
lolyoshi
  • 1,536
  • 3
  • 24
  • 42
  • what is line 33 `CalendarAdapter.java`? `getActivity()` is not null. your `calendar` might me null – Raghunandan Nov 01 '13 at 04:42
  • @Raghunandan: calendar isn't null. The line 33 is mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); Because getActivity() get null, so the context is null – lolyoshi Nov 01 '13 at 04:46
  • if it is in fragment user `getActivity()` instead of `context` and post that part of your code – Raghunandan Nov 01 '13 at 04:47
  • @Raghunandan: As I mentioned, I getActivity() in the fragment and it returns null. It happens after I change orientation – lolyoshi Nov 01 '13 at 04:49
  • @Raghunandan: when I swipe pager, it called the updateCurrentMonth() function in MyFragment class. The adapter is null. I tried to new the adapter but when I call getActivity(), it returns null – lolyoshi Nov 01 '13 at 04:53
  • Post your full code with your layouts. – Jitender Dev Nov 01 '13 at 05:19
  • @Raghunandan: moved to the onActivityCreated(), but it's not better – lolyoshi Nov 01 '13 at 06:35
  • @Brontok: my layouts are ok. The error just happens when changing orientation – lolyoshi Nov 01 '13 at 06:36
  • You could probably try putting the code in onAttach() or try reading about Fragment lifecycle in the official docs. ;) – Martin Marconcini Nov 01 '13 at 07:47

2 Answers2

5

Your own solution is extremely not recommended and you should never skip the call to super() in lifecycle methods.

Instead, figure out where your problem is.

Tips to do this:

  1. Override (and call Super!) every Activity/Fragment lifecycle method. OnCreate, OnResume, OnPause, OnStop, OnCreateView, OnViewCreated, Etc…

  2. Add a LOG line to each and run your app. See which ones get called and in which order.

  3. Rotate your device. Compare the results.

  4. Find why your member variable is not initialized, given the fact that on rotation, activities are destroyed and recreated.

  5. Be happy about the achievement of not using a terribly bad hack and the fact that your Android App will not mysteriously crash.

Martin Marconcini
  • 26,875
  • 19
  • 106
  • 144
  • My problem is maybe similar with this. If you have any another idea. You can show me because I can't find other ways to solve it http://stackoverflow.com/questions/13910826/viewpager-fragmentstatepageradapter-orientation-change – lolyoshi Nov 01 '13 at 08:04
-4

I finally found out how to fix for my error It's quite simple. I just need to override the onSaveInstanceState function in the activity and omit the super.onSaveInstanceState(outState); It looks like that

@Override
protected void onSaveInstanceState(final Bundle outState) {         
    //super.onSaveInstanceState(outState);
}
lolyoshi
  • 1,536
  • 3
  • 24
  • 42
  • 3
    No No No… this is bad :) Don't. Really bad. The Activity has a lifecycle and does things that you don't have to worry about. It does it when the methods get called. If you Override a method and you skip the super call, you're essentially preventing the Activity from performing its internal work. – Martin Marconcini Nov 01 '13 at 07:38
  • 1
    @MartínMarconcini: However, it works for me. It solved my error – lolyoshi Nov 01 '13 at 07:56