[英]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.