NullPointerException ViewPager 设置适配器

NullPointerException ViewPager SetAdapter

我正在向我正在处理的应用程序中的片段添加选项卡视图或 (ViewPager)。

我想将选项卡视图放在联系人片段中

我有一个打开的导航抽屉,您会看到选项列表...

首页

服务

联系

您点击的所有内容都会变成片段

然后在该片段中加载 .XML 文件,并使用相应的 class 对 .XML 文件中的所有内容进行编程。

我正在学习在线教程[单击此处][3]

显然是两年前的事了。 Android 从那以后代码发生了变化。我开始时遇到的错误比现在多一些。

我在使用 getSupportFragmentManager()getActionBar() 时遇到了问题,此时真的很困惑,所有导入都在那里。它不会认出那两个。显然,这让我觉得缺少了一些东西,但我不确定需要放什么才能让编译器看到那些需要的方法。

设置 ViewPager setAdapter 后我仍然得到 Null。

我想要完成的只是一个选项卡视图,其中有两个选项卡用于联系人和社交媒体。如果我能简单地了解选项卡正常工作所需的条件。

我已经搜索过问题,但它们并没有完全触及我的具体问题,因此我正在寻求帮助。非常感谢任何帮助。

FragmentContact

package com.megliosolutions.bitsnbytes.Fragments;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.megliosolutions.bitsnbytes.MainActivity;
import com.megliosolutions.bitsnbytes.R;
import com.megliosolutions.bitsnbytes.ViewPagerClasses.TabsPagerAdapter;

/**
 * Created by Jarvis on 6/21/15.
 */
public class FragmentContact extends Fragment {

    private ViewPager viewPager;
    TabsPagerAdapter mAdapter;
    private ActionBar actionBar;

    private String[] tabs = {"Contact", "Social Media"};

    public static FragmentContact newInstance(){

        FragmentContact fragment = new FragmentContact();
        return fragment;

    }

    public FragmentContact(){};

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

        View rootView = inflater.inflate(R.layout.fragment_contact, container, false);

        LoadTabs(rootView);

        return rootView;
    }

    private void LoadTabs(View rootView) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        // Initilization
        viewPager = (ViewPager) rootView.findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(fragmentManager);

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener((ActionBar.TabListener) this));
        }
    }

    @Override
    public void onAttach(FragmentActivity activity) {
        super.onAttach(activity);

        ((MainActivity) activity).onSectionAttached(5);
    }


}

TabsPagerAdapter

package com.megliosolutions.bitsnbytes.ViewPagerClasses;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.View;

/**
 * Created by Jarvis on 6/28/15.
 */
public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {

        super(fm);
    }

    @Override
    public Fragment getItem(int index) {

        switch (index) {
            case 0:
                // Contact fragment activity
                return new ContactFragment();
            case 1:
                // Social Media fragment activity
                return new SocialMediaFragment();

        }

        return null;
    }

    @Override
    public int getCount() {
        // get item count - equal to number of tabs
        return 2;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return false;
    }

}

主要活动

package com.megliosolutions.bitsnbytes;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.megliosolutions.bitsnbytes.Fragments.FragmentAbout;
import com.megliosolutions.bitsnbytes.Fragments.FragmentContact;
import com.megliosolutions.bitsnbytes.Fragments.FragmentHome;
import com.megliosolutions.bitsnbytes.Fragments.FragmentProducts;
import com.megliosolutions.bitsnbytes.Fragments.FragmentServices;
import com.megliosolutions.bitsnbytes.Fragments.FragmentWarranties;


public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {


    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;






    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;
    private ActionBarDrawerToggle mDrawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));


    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();

        if(position == 0) {
            fragmentManager.beginTransaction()
                    .replace(R.id.container, FragmentHome.newInstance())
                    .commit();
        }
        else if(position == 1){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, FragmentServices.newInstance())
                    .commit();
        }
        else if(position == 2){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, FragmentProducts.newInstance())
                    .commit();
        }

        else if(position == 3){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, FragmentWarranties.newInstance())
                    .commit();
        }

        else if(position == 4){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, FragmentContact.newInstance())
                    .commit();
        }
        else if(position == 5){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, FragmentAbout.newInstance())
                    .commit();
        }




    }



    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.title_section1);
                break;
            case 2:
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                mTitle = getString(R.string.title_section3);
                break;
            case 4:
                mTitle = getString(R.string.title_section4);
                break;
            case 5:
                mTitle = getString(R.string.title_section5);
                break;
            case 6:
                mTitle = getString(R.string.title_section6);
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

}

现在 onNavigationDrawerItemSelected() 中的 FragmentContact.newInstance() 出现问题

06-28 15:35:24.695  11744-11744/com.megliosolutions.bitsnbytes E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.megliosolutions.bitsnbytes, PID: 11744
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
            at com.megliosolutions.bitsnbytes.Fragments.FragmentContact.LoadTabs(FragmentContact.java:55)
            at com.megliosolutions.bitsnbytes.Fragments.FragmentContact.onCreateView(FragmentContact.java:43)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:458)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

来自 logcat 错误,其明确的 ViewPager 不存在于 R.layout.fragment_contact 中。请验证。

因为我需要引用它存在于 activity_main.xml 而不是当前片段上的 viewPager,所以我设法解决了这个错误:

我添加了一个新视图的声明,引用 activity ViewPager 所在的位置如下:

  View viewNext = inflater.inflate(R.layout.activity_main, container, false);

然后,我根据上面的声明声明了viewPager:

  viewPager = (ViewPager) viewNext.findViewById(R.id.viewPager);

之后,我设置了适配器。