[英]Not able to pass data from activity to fragment
我正在開發一個應用程序,其中有一個Activity
最初加載Fragment
。 我在活動中獲得 IMEI 號、緯度、經度,並將該數據傳遞到片段中,並在片段中獲取該數據,但是當我獲取數據時出現空指針異常。
最初,我的帳戶活動加載注冊片段,並且我正在將帳戶活動中的數據發送到注冊片段
// 發送數據的活動代碼
// 在賬戶活動中設置注冊片段
changeFragments(new SignupFragment());
// 現在調用函數 GeoLocation 並將其發送到注冊片段
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);
}
// 現在注冊 Fragment > 我在調用 Api 的地方得到這些字段
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");
}
我在這里收到空指針異常。
changeFragments(fragobj);
更改這一行,因為如果您當時使用新的 SingupFragment 它將創建新對象
您應該傳遞片段的實例而不是創建新的實例,例如:-
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() 方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.