有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓将值从activity传递到fragment给出错误java。lang.NullPointerException

大家好, 我有一个程序将变量的值从活动类传递到片段,我做了太多类似这样的研究Send data from activity to fragment in 安卓,但它总是给我一个错误,我不知道为什么

这是我的活动公司页面活动。爪哇

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 安卓.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
                                                                          at 安卓.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
                                                                          at 安卓.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
                                                                          at 安卓.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
                                                                          at 安卓.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
                                                                          at 安卓.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
                                                                          at 安卓.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
                                                                          at 安卓.support.v4.view.ViewPager.populate(ViewPager.java:1240)
                                                                          at 安卓.support.v4.view.ViewPager.populate(ViewPager.java:1088)
                                                                          at 安卓.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
                                                                          at 安卓.view.View.measure(View.java:16677)
                                                                          at 安卓.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at 安卓.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:700)
                                                                          at 安卓.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
                                                                          at 安卓.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1364)
                                                                          at 安卓.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:765)
                                                                          at 安卓.view.View.measure(View.java:16677)
                                                                          at 安卓.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at 安卓.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                          at 安卓.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                          at 安卓.view.View.measure(View.java:16677)
                                                                          at 安卓.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at 安卓.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                                          at 安卓.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                                          at 安卓.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                                          at 安卓.view.View.measure(View.java:16677)
                                                                          at 安卓.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at 安卓.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                          at 安卓.view.View.measure(View.java:16677)
                                                                          at 安卓.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at 安卓.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                                          at 安卓.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                                          at 安卓.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                                          at 安卓.view.View.measure(View.java:16677)
                                                                          at 安卓.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
                                                                          at 安卓.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                          at com.安卓.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2421)
                                                                          at 安卓.view.View.measure(View.java:16677)
                                                                          at 安卓.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1927)
                                                                          at 安卓.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1119)
                                                                          at 安卓.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1301)
                                                                          at 安卓.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1006)
                                                                          at 安卓.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5652)
                                                                          at 安卓.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
                                                                          at 安卓.view.Choreographer.doCallbacks(Choreographer.java:574)
                                                                          at 安卓.view.Choreographer.doFrame(Choreographer.java:544)
                                                                          at 安卓.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
                                                                          at 安卓.os.Handler.handleCallback(Handler.java:733)
                                                                          at 安卓.os.Handler.dispatchMessage(Handler.java:95)
                                                                          at 安卓.os.Looper.loop(Looper.java:136)
                                                                          at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)

请帮帮我,我被困在这里了。 我已经试过这个代码了`

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

这个呢

 Bundle bundle = this.getArguments();

    companyName = bundle.getString("CompanyName");

但它总是一次又一次地给我同样的错误

这是我的一节适应课

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) 个答案

  1. # 1 楼答案

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

    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参数创建一个构造函数:

    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;
            }
        }
    
        ...
    }
    

    现在,您可以使用构造函数传递包:

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