在Fragment中修改FragmentActivity时ViewPager NullPointerException

时间:2013-09-23 01:07:20

标签: android-fragments android-viewpager

我正在尝试修改托管视图寻呼机的旧FragmentActivity,其中包含片段中的3个列表视图。 Fragment类的代码类似于Activity。实际上,在将现有的Android应用程序转换为使用片段时,我认为将代码从活动的回调方法移动到片段的相应回调方法就足够了。但它没有用。我在

行获得了NullPointerException
mViewPager.setAdapter(mAppSectionsPagerAdapter);

这是代码:

public class FragmentAllEvents extends Fragment implements ActionBar.TabListener 
{
    AppSectionsPagerAdapter mAppSectionsPagerAdapter;

    // JSON Node names
    private static final String TAG_UID = "uid";
    private static final String TAG_LOGO = "logo";
    private static final String TAG_POKUID = "pokuid";

    static ArrayList<HashMap<String, String>> userList;
    ArrayList<HashMap<String, String>> userListTotal;
    HashMap<String, String> userSelected;
    EventsFunctions eventsFunctions;
    UserFunctions userFunctions;
    /**
     * The {@link ViewPager} that will display the three primary sections of the app, one at a
     * time.
     */
    ViewPager mViewPager;
    static ListView lv;
    ActionBar actionBar;

    //Context context = this;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        View v = inflater.inflate(R.layout.all_events_main, container, false);

        Log.e("AllEventsFragmentActivity Report", "Entering AllEventsFragments");
        // Create the adapter that will return a fragment for each of the three primary sections
        // of the app.
        //FragmentManager fm = getSupportFragmentManager();
        mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getFragmentManager());

        // Set up the action bar.
        actionBar = getActivity().getActionBar();

        // Specify that the Home/Up button should not be enabled, since there is no hierarchical
        // parent.
        actionBar.setHomeButtonEnabled(true);

        // Specify that we will be displaying tabs in the action bar.
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Set up the ViewPager, attaching the adapter and setting up a listener for when the
        // user swipes between sections.
        mViewPager = (ViewPager) getActivity().findViewById(R.id.pager_main);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);
        // Defining a listener for pageChange 
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() 
        {
            [...]
        });

        [...]
}

在这个类的上一个版本中,我使用FragmentActivity而不是Fragment扩展了FragmentAllEvents。

1 个答案:

答案 0 :(得分:2)

看起来,mViewPager未填充且为NULL。如果pager_main位于all_events_main布局中,则需要使用v.findViewById(R.id.pager_main)