繁体   English   中英

尝试将数据从活动传递到片段Android时返回null指针

[英]null pointer when trying to pass data from activity to fragment Android

我正在尝试将数据从活动传递到片段。 我到处都在寻找解决方案,但是无法为我工作。 我尝试使用捆绑软件,但出现空指针异常。

活动类别:

public class RouteOutput extends AppCompatActivity {


private SectionsPagerAdapter mSectionsPagerAdapter;

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle ways = getIntent().getExtras();
    if(ways==null) {
        return;
    }
    System.out.println("START LAT: " + ways.getDouble("start_lat"));



    ways.putDouble("start_lat", ways.getDouble("start_lat"));
    ways.putDouble("start_lon", ways.getDouble("start_lon"));
    ways.putStringArrayList("coords", ways.getStringArrayList("coords"));

    if(!(ways.getDouble("altend") == 0)) {
        ways.putDouble("altend_lat", ways.getDouble("altend_lat"));
        ways.putDouble("altend_lon", ways.getDouble("altend_lon"));
    }
    FragmentMapOutput frag = new FragmentMapOutput();
    frag.setArguments(ways);

在我的片段类中,我有这个:

View view = inflater.inflate(R.layout.fragment_map_output, container, false);
    MapboxAccountManager.start(getContext(), getString(R.string.access_token));

    mView = (MapView) view.findViewById(R.id.mapview);
    mView.onCreate(savedInstanceState);
    mView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(MapboxMap mapboxMap) {

            mMap = mapboxMap;

            Bundle bundle = getArguments();
            double startlat = bundle.getDouble("start_lat");
            System.out.println("BUNDLE: " + startlat);

我正在使用android tablayout模板,并且在此活动中有两个片段。

我得到的错误如下:

W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.os.BaseBundle.getDouble(java.lang.String)' on a null object reference

请尝试创建一个新的Bundle实例,它将实例化,而不是使用您在活动中收到的实例

Bundle newWays=new Bundle();
  Bundle ways = getIntent().getExtras();
if(ways==null) {
    return;
}


 newWays.putDouble("start_lat", ways.getDouble("start_lat"));
newWays.putDouble("start_lon", ways.getDouble("start_lon"));
newWays.putStringArrayList("coords", ways.getStringArrayList("coords"));

if(!(ways.getDouble("altend") == 0)) {
    newWays.putDouble("altend_lat", ways.getDouble("altend_lat"));
    newWays.putDouble("altend_lon", ways.getDouble("altend_lon"));
}
FragmentMapOutput frag = new FragmentMapOutput();
frag.setArguments(newWays);

除此之外,我不确定是否看到任何错误,希望对您有所帮助

捆绑包位于onMapReady方法中。 它将为空。

您应该从onCreateView中的捆绑包中获取数据(LayoutInflater充气器,ViewGroup容器,捆绑包saveInstance)

并将数据分配给成员对象,然后在onMapReady中使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM