将值从活动传递给片段会产生错误java.lang.NullPointerException

时间:2017-09-20 16:24:34

标签: java android android-fragments

好日子,伙计们, 我有一个程序将变量值从活动类传递给片段,我做了太多像这样的Send data from activity to fragment in android,但它总是给我一个错误,我不知道为什么,

这是我的活动CompanyPageActivity.java

private SectionsPagerAdapter mSectionsPagerAdapter;

String companyName, companyDescripiton, lat, lng, contact1, contact2, contact3, contact4, email, tag1, tag2, tag3, tag4,tag5,website;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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


    Bitmap bitmap = (Bitmap) getIntent().getParcelableExtra("BitmapImage");

    companyName = getIntent().getExtras().getString("CompanyName");
    companyDescripiton = getIntent().getExtras().getString("Description");
    lat  = getIntent().getExtras().getString("latitude");
    lng = getIntent().getExtras().getString("longtitude");
    contact1 = getIntent().getExtras().getString("contact1");
    contact2 = getIntent().getExtras().getString("contact2");
    contact3 = getIntent().getExtras().getString("contact3");
    contact4 = getIntent().getExtras().getString("contact4");
    email = getIntent().getExtras().getString("email");
    tag1 = getIntent().getExtras().getString("tag1");
    tag2 = getIntent().getExtras().getString("tag2");
    tag3 = getIntent().getExtras().getString("tag3");
    tag4 = getIntent().getExtras().getString("tag4");
    tag5 = getIntent().getExtras().getString("tag5");
    website = getIntent().getExtras().getString("website");

    Bundle bundleTitle = new Bundle();
    bundleTitle.putString("CompanyName", companyName);
    bundleTitle.putString("Description", companyDescripiton);
    bundleTitle.putString("contact1",contact1);
    bundleTitle.putString("contact2",contact2);
    bundleTitle.putString("contact3",contact3);
    bundleTitle.putString("contact4",contact4);
    bundleTitle.putString("tag1",tag1);
    bundleTitle.putString("tag2",tag2);
    bundleTitle.putString("tag3",tag3);
    bundleTitle.putString("tag4",tag4);
    bundleTitle.putString("tag5",tag5);
    bundleTitle.putString("website",website);
    bundleTitle.putString("email",email);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] byteArray = stream.toByteArray();

    bundleTitle.putByteArray("logo", byteArray);

    TabTitle tabTitle = new TabTitle();
    tabTitle.setArguments(bundleTitle);

    Bundle bundleLocation = new Bundle();
    bundleLocation.putString("lat", lat);
    bundleLocation.putString("lng", lng);
    bundleLocation.putString("companyName", companyName);

    TabLocation tabLocation = new TabLocation();
    tabLocation.setArguments(bundleLocation);


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

这是我的片段

ImageView logo;
TextView companyNametxt, companyDescripitontxt, contacts, emailtxt, tags, websitetxt;

String companyName, companyDescripiton, contact1, contact2, contact3, contact4, email, tag1, tag2, tag3, tag4,tag5,website;

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

    companyNametxt = (TextView)rootView.findViewById(R.id.companyName);
    companyDescripitontxt = (TextView)rootView.findViewById(R.id.companyDescription);
    contacts = (TextView)rootView.findViewById(R.id.contact);
    emailtxt = (TextView)rootView.findViewById(R.id.email);
    tags = (TextView)rootView.findViewById(R.id.tag);
    websitetxt = (TextView)rootView.findViewById(R.id.website);
    logo = (ImageView) rootView.findViewById(R.id.logo);

    companyName = getArguments().getString("CompanyName"); //line number 42
    companyDescripiton = getArguments().getString("Description");
    contact1 = getArguments().getString("contact1");
    contact2 = getArguments().getString("contact2");
    contact3 = getArguments().getString("contact3");
    contact4 = getArguments().getString("contact4");
    email = getArguments().getString("email");
    tag1 = getArguments().getString("tag1");
    tag2 = getArguments().getString("tag2");
    tag3 = getArguments().getString("tag3");
    tag4 = getArguments().getString("tag4");
    tag5 = getArguments().getString("tag5");
    website = getArguments().getString("website");

    byte[] byteArray  = getArguments().getByteArray("image");
    Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

    companyNametxt.setText(companyName);
    companyDescripitontxt.setText(companyDescripiton);
    contacts.setText("Contact number(s): \n"+contact1+"\t"+contact2+"\n"+contact3+"\t"+contact4);
    tags.setText("Tags: "+tag1+" "+tag2+" "+tag3+" "+tag4+" "+tag5);
    websitetxt.setText(website);
    emailtxt.setText(email);

    logo.setImageBitmap(bitmap);

    return rootView;
}

但它总是给我这个错误

java.lang.NullPointerException
                                                                          at com.gawapa.servicefinder.pageTabs.TabTitle.onCreateView(TabTitle.java:42)
                                                                          at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
                                                                          at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
                                                                          at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
                                                                          at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
                                                                          at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
                                                                          at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
                                                                          at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
                                                                          at android.support.v4.view.ViewPager.populate(ViewPager.java:1240)
                                                                          at android.support.v4.view.ViewPager.populate(ViewPager.java:1088)
                                                                          at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
                                                                          at android.view.View.measure(View.java:16677)
                                                                          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:700)
                                                                          at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
                                                                          at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1364)
                                                                          at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:765)
                                                                          at android.view.View.measure(View.java:16677)
                                                                          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                          at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                          at android.view.View.measure(View.java:16677)
                                                                          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                                          at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                                          at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                                          at android.view.View.measure(View.java:16677)
                                                                          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                          at android.view.View.measure(View.java:16677)
                                                                          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                                          at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                                          at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                                          at android.view.View.measure(View.java:16677)
                                                                          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                          at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2421)
                                                                          at android.view.View.measure(View.java:16677)
                                                                          at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1927)
                                                                          at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1119)
                                                                          at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1301)
                                                                          at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1006)
                                                                          at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5652)
                                                                          at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
                                                                          at android.view.Choreographer.doCallbacks(Choreographer.java:574)
                                                                          at android.view.Choreographer.doFrame(Choreographer.java:544)
                                                                          at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
                                                                          at android.os.Handler.handleCallback(Handler.java:733)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                          at android.os.Looper.loop(Looper.java:136)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5433)
                                                                          at java.lang.reflect.Method.invokeNative(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:515)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
请帮助我T_T我被困在这里。 我已经尝试过这段代码了

companyName = this.getArguments().getString("CompanyName");

和这一个

 Bundle bundle = this.getArguments();

    companyName = bundle.getString("CompanyName");

但它总是一次又一次地给我一个错误

这是我的SectionsPagerAdapter类

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                TabTitle tabTitle = new TabTitle();
                return tabTitle;
            case 1:
                TabPosts tabPosts = new TabPosts();
                return tabPosts;
            case 2:
                TabLocation tabLocation = new TabLocation();
                return tabLocation;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "ABOUT";
            case 1:
                return "POSTS";
            case 2:
                return "LOCATION";
        }
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

正如@ daniel-nugent所说,您需要将捆绑包传递给ViewPager适配器创建的Fragment。发生错误是因为您正在创建另一个片段并使用以下命令将包传递到适配器外部:

Bundle bundleTitle = new Bundle();
...
TabTitle tabTitle = new TabTitle();
tabTitle.setArguments(bundleTitle);

Bundle bundleLocation = new Bundle();
...
TabLocation tabLocation = new TabLocation();
tabLocation.setArguments(bundleLocation);

但在适配器中,您没有通过任何捆绑(请阅读 评论 ):

public class SectionsPagerAdapter extends FragmentPagerAdapter {
  ...
  @Override
  public Fragment getItem(int position) {
    switch (position) {
      case 0:
        TabTitle tabTitle = new TabTitle();
        // Where is my Arguments?
        return tabTitle;
      case 1:
        TabPosts tabPosts = new TabPosts();
        return tabPosts;
      case 2:
        TabLocation tabLocation = new TabLocation();
        // Please, give me the arguments!
        return tabLocation;
      default:
        return null;
    }
  }
  ...
}

因此,您需要创建并设置适配器的参数。您可以通过SectionsPagerAdapter构造函数传递Bundle。因此,使用Bundle参数创建一个构造函数:

public class SectionsPagerAdapter extends FragmentPagerAdapter {

  private Bundle bundleTitle;
  private Bundle bundleLocation;

    public SectionsPagerAdapter(FragmentManager fm, Bundle bundleTitle, Bundle bundleLocation) {
        super(fm);

      // save the bundle to local variable
      this.bundleTitle = bundleTitle;
      this.bundleLocation = bundleLocation;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                TabTitle tabTitle = new TabTitle();
                // set the argument here
                tabTitle.setArguments(bundleTitle);
                return tabTitle;
            case 1:
                TabPosts tabPosts = new TabPosts();
                return tabPosts;
            case 2:
                TabLocation tabLocation = new TabLocation();
                // set the argument here
                tabTitle.setArguments(bundleLocation);
                return tabLocation;
            default:
                return null;
        }
    }

    ...
}

现在您可以使用构造函数来传递Bundle:

mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), bundleTitle, bundleLocation);