2017-02-13 47 views
0

我試圖將數據從活動傳遞到片段。我環顧瞭解解決方案,但無法爲我工作。我試過使用這個包,但我得到空指針異常。嘗試將數據從活動傳遞到片段時出現空指針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模板,並在此activty兩個片段。

我得到的錯誤是下面:

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

你的FragmenTransaction是怎麼樣的? –

+0

試一試這個解決方案http://stackoverflow.com/questions/32031178/nullpointerexception-on-android-os-bundle –

+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); 

除了一由此,我不確定是否看到任何錯誤, 希望它有幫助

0

Bundle是在裏面的MapReady方法。它將是空的。

你應該從包中onCreateView

數據(LayoutInflater吹氣,ViewGroup中容器,包savedInstance)和數據分配給成員對象,然後在onMapReady使用。

相關問題