2017-09-26 97 views
-4

我正在開發一個應用程序,其中有一個Activity,最初載入Fragment。我在活動中獲取IMEI No,Latitude,Longitude,並將該數據傳遞到片段中,並將片段中的數據獲取,但獲取數據時收到空指針異常。無法將數據從活動傳遞到片段

最初我的賬戶活動載荷註冊片段且我從帳戶活動將數據發送至註冊片段

//活動代碼從

發送數據//在帳戶活動

設置註冊片段
changeFragments(new SignupFragment()); 

//現在調用函數地理定位和發送到註冊片段

public void GeoLocation() { 

    Bundle bundle = new Bundle(); 
    bundle.putString("imei_no", imei_number); 
    bundle.putString("lat",latitude.toString()); 
    bundle.putString("long",longitude.toString()); 
    bundle.putString("postal_code",postalCode); 

    SignupFragment fragObj = new SignupFragment(); 
    fragObj.setArguments(bundle); 
} 

//現在註冊片段>我收到這些領域,我叫阿比

private void callApi() { 

    String imei_no = getArguments().getString("imei_no"); 
    String latitude = getArguments().getString("lat"); 
    String longitude = getArguments().getString("long"); 
    String postal_code = getArguments().getString("postal_code"); 
} 

我在這裏獲得空指針異常。

回答

0
changeFragments(fragobj); 

改變這一行,因爲如果你在那個時候使用新SingupFragment它創建新的對象

0

你應該通過片段的實例,而不是創造一個像新: -

public void GeoLocation() { 

     Bundle bundle = new Bundle(); 
      bundle.putString("imei_no", imei_number); 
      bundle.putString("lat",latitude.toString()); 
      bundle.putString("long",longitude.toString()); 
      bundle.putString("postal_code",postalCode); 

      SignupFragment fragobj = new SignupFragment(); 
      fragobj.setArguments(bundle); 

    changeFragments(fragobj); 
    } 

這裏我調用GeoLocation中的changeFragments()方法。