我正在尝试将数据从活动传递到片段。我已经四处寻找解决方案,但无法让这个为我工作。我已尝试使用该捆绑包但我得到空指针异常。
活动类:
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
答案 0 :(得分:0)
请尝试创建一个新的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);
除此之外,我不确定我有什么不对, 希望它有所帮助
答案 1 :(得分:0)
Bundle在onMapReady方法中。它将为空。
你应该从onCreateView(LayoutInflater inflater,ViewGroup容器,Bundle savedInstance)中的bundle获取数据
并将数据分配给成员对象,然后在onMapReady中使用。