将数据从Activity传递到Fragment by Bundle

时间:2014-03-24 05:35:11

标签: android android-fragments nullpointerexception bundle

我正在开发一个使用class DetailActivity extends FragmentActivity和五个片段{DetailHeader, DetailInfo, DetailMap, DetailHelp, DetailMore}的Android应用。当我尝试通过Bundle将数据从DetailActivity传递到DetailHeader时遇到错误。此错误在班级"NullPointerException"中显示:DetailHeader。请帮我。对不起我的英语,这不好。

这是DetailActivity的源代码:

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;

public class DetailActivity extends FragmentActivity {

public static final int FRAGMENT_HEADER = 0;
public static final int FRAGMENT_INFO = 1;
public static final int FRAGMENT_MAP = 2;
public static final int FRAGMENT_HELP = 3;
public static final int FRAGMENT_MORE = 4;
public static final int FRAGMENTS = 5;
private FragmentPagerAdapter _fragmentPagerAdapter;
private ViewPager _viewPager;
private List<Fragment> _fragments = new ArrayList<Fragment>();
public static final String TAG_NAME = "FestivalName";
private String festivalName=" Alo";

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

    // Create fragments.
            _fragments.add(FRAGMENT_HEADER, new DetailHeader());    
            _fragments.add(FRAGMENT_INFO, new DetailInfo());
            _fragments.add(FRAGMENT_MAP, new DetailMap());
            _fragments.add(FRAGMENT_HELP, new DetailHelp());
            _fragments.add(FRAGMENT_MORE, new DetailMore());

            // Setup the fragments, defining the number of fragments, the screens
            // and titles.
            _fragmentPagerAdapter = new FragmentPagerAdapter(
                    getSupportFragmentManager()) {
                @Override
                public int getCount() {
                    return FRAGMENTS;
                }

                @Override
                public Fragment getItem(final int position) {
                    return _fragments.get(position);
                }

                @Override
                public CharSequence getPageTitle(final int position) {
                    switch (position) {
                    case FRAGMENT_HEADER:
                        return "Title Header";
                    case FRAGMENT_INFO:
                        return "Title Info";
                    case FRAGMENT_MAP:
                        return "Title Map";
                    case FRAGMENT_HELP:
                        return "Title Help";
                    case FRAGMENT_MORE:
                        return "Title More";
                    default:
                        return null;
                    }
                }
            };


            _viewPager = (ViewPager) findViewById(R.id.pager);
            _viewPager.setAdapter(_fragmentPagerAdapter);
            try {
                Bundle bundle=new Bundle();
                bundle.putString(TAG_NAME,"Alo");
                DetailHeader header = new DetailHeader();
                header.setArguments(bundle);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.detail, menu);
    return true;
}



  }

这是DetailHeader的源代码:

public class DetailHeader extends Fragment {

ImageView imageView;
TextView textHeader;
public String FestivalName;

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

    View view = inflater.inflate(R.layout.detail_header, null);
    imageView =(ImageView)view.findViewById(R.id.grid_outer_image);
    textHeader =(TextView)view.findViewById(R.id.grid_inner_text);
    imageView.setImageResource(R.drawable.dengiong);
    try {
        Bundle bundle = this.getArguments();
        FestivalName = bundle.getString(DetailActivity.TAG_NAME);
        //FestivalName = getArguments().getString(DetailActivity.TAG_NAME);
        textHeader.setText(FestivalName);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        //Log.e("Detail Header", e.getMessage());
        e.printStackTrace();
    }

    return view;
}

 }

这是我的错误:

java.lang.NullPointerException
at fu.android.example.travelvnproject_v01.Fragment.DetailHeader.onCreateView(DetailHeader.java:41)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
at android.view.View.measure(View.java:15454)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5108)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15454)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
at android.view.View.measure(View.java:15454)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5108)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2397)
at android.view.View.measure(View.java:15454)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1987)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1228)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1401)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1121)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4598)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
at android.view.Choreographer.doCallbacks(Choreographer.java:555)
at android.view.Choreographer.doFrame(Choreographer.java:525)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4950)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:997)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:764)
at dalvik.system.NativeStart.main(Native Method)

这是DetailActivity XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<!-- This title strip will display the currently visible page title, as well as the page titles for adjacent pages. -->
<android.support.v4.view.PagerTitleStrip
    android:id="@+id/pager_title_strip"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top" />

</android.support.v4.view.ViewPager>

这是DetailHeader XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<ImageView
    android:id="@+id/grid_outer_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
     />

<RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" >
</RelativeLayout>

<TextView
    android:id="@+id/grid_inner_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dip"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="#AA000000"
    android:padding="12dip"
    android:text="some text"
    android:textColor="#ffffffff" />

 </RelativeLayout>

1 个答案:

答案 0 :(得分:0)

因为你正在创建片段的两个不同对象

 _fragments.add(FRAGMENT_HEADER, new DetailHeader()); // you are return this fragment which doesn't have bundle 

        try {
            Bundle bundle=new Bundle();
            bundle.putString(TAG_NAME,"Alo");
            DetailHeader header = new DetailHeader(); // you are set bundle to this fragment which not return  
            header.setArguments(bundle);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

所以这样做

public class DetailActivity extends FragmentActivity {

public static final int FRAGMENT_HEADER = 0;
public static final int FRAGMENT_INFO = 1;
public static final int FRAGMENT_MAP = 2;
public static final int FRAGMENT_HELP = 3;
public static final int FRAGMENT_MORE = 4;
public static final int FRAGMENTS = 5;
private FragmentPagerAdapter _fragmentPagerAdapter;
private ViewPager _viewPager;
private List<Fragment> _fragments = new ArrayList<Fragment>();
public static final String TAG_NAME = "FestivalName";
private String festivalName = " Alo";

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

    DetailHeader detailHeader = new DetailHeader();

    // do same for all fragment if you pass value with fragment 

    // Create fragments.
    _fragments.add(FRAGMENT_HEADER, detailHeader);
    _fragments.add(FRAGMENT_INFO, new DetailInfo());
    _fragments.add(FRAGMENT_MAP, new DetailMap());
    _fragments.add(FRAGMENT_HELP, new DetailHelp());
    _fragments.add(FRAGMENT_MORE, new DetailMore());

    // Setup the fragments, defining the number of fragments, the screens
    // and titles.
    _fragmentPagerAdapter = new FragmentPagerAdapter(
            getSupportFragmentManager()) {
        @Override
        public int getCount() {
            return FRAGMENTS;
        }

        @Override
        public Fragment getItem(final int position) {
            return _fragments.get(position);
        }

        @Override
        public CharSequence getPageTitle(final int position) {
            switch (position) {
            case FRAGMENT_HEADER:
                return "Title Header";
            case FRAGMENT_INFO:
                return "Title Info";
            case FRAGMENT_MAP:
                return "Title Map";
            case FRAGMENT_HELP:
                return "Title Help";
            case FRAGMENT_MORE:
                return "Title More";
            default:
                return null;
            }
        }
    };

    _viewPager = (ViewPager) findViewById(R.id.pager);
    _viewPager.setAdapter(_fragmentPagerAdapter);
    try {
        Bundle bundle = new Bundle();
        bundle.putString(TAG_NAME, "Alo");
        detailHeader.setArguments(bundle); // its same fragment which you
                                            // are returning
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}