传递数据时,将数据从一个片段传递到另一个片段不起作用

时间:2015-03-15 11:58:18

标签: android android-fragments

我有一个片段fragmentA,我有一个gridview。用户点击网格的一行,我读取第一列的值并将其传递给另一个片段MapFragment。当我在调试模式下运行时,我可以看到fragmentA中的数据被传递给主活动,应用程序崩溃了。

代码有什么问题?我错过了什么吗?

  

致命的例外:主要       显示java.lang.NullPointerException               在com.text.MainActivity.SendData(MainActivity.java:51)               在com.test.fragmentAFragment $ 1.onItemClick(BurnScheduleFragment.java:50)               在android.widget.AdapterView.performItemClick(AdapterView.java:301)               在android.widget.AbsListView.performItemClick(AbsListView.java:1539)               在android.widget.AbsListView $ PerformClick.run(AbsListView.java:3332)               在android.widget.AbsListView $ 1.run(AbsListView.java:4554)               在android.os.Handler.handleCallback(Handler.java:725)               在android.os.Handler.dispatchMessage(Handler.java:92)               在android.os.Looper.loop(Looper.java:176)               在android.app.ActivityThread.main(ActivityThread.java:5279)               at java.lang.reflect.Method.invokeNative(Native Method)               在java.lang.reflect.Method.invoke(Method.java:511)               在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1102)               在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)               在dalvik.system.NativeStart.main(本地方法)

我有一个界面

 `public interface Communicate {
    public void SendData(String place);
}

在MapFragment中

public class MapFragment extends Fragment {

    private MapView map;

    HashMap markerMap = new HashMap();
    Marker marker;

    public MapFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = this.getArguments();

    }

    public void Show(String title)
    {

        Marker showMarkerOnMap = (Marker)markerMap.get(title);
        showMarkerOnMap.showInfoWindow();
    }

    private void CreateMarkers(){

        GoogleMap gMap = map.getMap();
        gMap.setMyLocationEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        marker = gMap.addMarker(new MarkerOptions().title("One")
                .snippet("description")
                .position(new LatLng( 0, 0)));
        markerMap.put("One", marker);

         }

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

        if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getApplicationContext()) == ConnectionResult.SUCCESS) {
            //Initialze mapview
            MapsInitializer.initialize(getActivity());
            map = (MapView) view.findViewById(R.id.mapView);
            map.onCreate(savedInstanceState);
            CreateMarkers();

        } else {
            Toast.makeText(getActivity(), "Please install google play services", Toast.LENGTH_LONG).show();
        }
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        map.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        map.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        map.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        map.onLowMemory();
    }
}

在我的MainAcyivity中我有

将SendData实现为

public void SendData(String place)
{
    FragmentManager fragmentManager = getSupportFragmentManager();
    MapFragment mapFragment = (MapFragment)fragmentManager.findFragmentById(R.id.mapView);
    mapFragment.Show(place);
}

我在MapFragment中添加了Show方法

  public void Show(String title)
{

    Marker showMarkerOnMap = (Marker)markerMap.get(title);
    showMarkerOnMap.showInfoWindow();
}



public class MainActivity extends ActionBarActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks, Communicate {

private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;


@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));
}

public void SendData(String place)
{
    FragmentManager fragmentManager = getSupportFragmentManager();
    MapFragment mapFragment = (MapFragment)fragmentManager.findFragmentById(R.id.mapView);
    mapFragment.Show(place);
}

@Override
public void onNavigationDrawerItemSelected(int position)
{
    // update the main content by replacing fragments

    Fragment fragment = null;
    switch (position){ 
        case 0:
            fragment= new MapFragment();
            break;
        case 1:
            fragment = new BFragment();
            break;
        case 2:                 
            break; 
        default:
            fragment =  new AFragment();
            break;
    }
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.container, fragment)
            .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;
    }
}

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



    @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));
    }
}

}

`

Map_fragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</RelativeLayout>

2 个答案:

答案 0 :(得分:1)

您的片段为空。否则,NullPointerException将由Fragment而不是Activity引起。您是否使用正确的ID(容器ID或XML-ID)调用getFragmentById?

答案 1 :(得分:0)

要将值从活动传递到片段或片段到片段,请使用setArgument。

Bundle bundle = new Bundle(); bundle.putInt(key,value); fragment.setArguments(束);

How to pass values between Fragments

我希望它会对你有所帮助。