[英]Why am I Getting a Null Pointer Exception When I Retrieve Bundle Arguments?
I'm trying to create a fragment within MyActivity
, passing it the data it needs to display.我正在尝试在MyActivity
创建一个片段,将它需要显示的数据传递给它。 I'm currently trying to pack all the data in a bundle through the static method newInstance()
我目前正在尝试通过静态方法newInstance()
将所有数据打包成一个包
When I open the activity however, I get a Null Pointer Exception when I try and unpack the bundle in onCreateView()
但是,当我打开活动时,当我尝试在onCreateView()
解压缩包时,出现空指针异常
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String, int)' on a null object reference
This occurs on the first call to getInt()
which leads me to believe getArguments()
is returning a null bundle for some reason, and I can't reason why it would.这发生在第一次调用getInt()
,这让我相信getArguments()
由于某种原因正在返回一个空包,我无法解释为什么会这样。
MyActivity.java我的活动.java
/* Create Status Bar fragment */
FragmentManager fragMngr = getSupportFragmentManager();
frag = (StatusBarFragment)fragMngr.findFragmentById(R.id.f_container2);
if (frag == null)
{
frag = StatusBarFragment.newInstance(player.getMoney(),
player.getHealth(),
player.getEquipmentMass());
fragMngr.beginTransaction().add(R.id.f_container2, frag).commit();
}
StatusBarFragment.java状态栏片段.java
public class StatusBarFragment extends Fragment
{
private static final String MONEY = "vg.my.citruscode.money";
private static final String HEALTH = "vg.my.citruscode.health";
private static final String EQUIPMENT_MASS = "vg.my.citruscode.equipmentMass";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View parentView = inflater.inflate(R.layout.fragment_status_bar, container, false);
Bundle args = getArguments();
// Omitted methods which update UI Elements
updateMoney(args.getInt(MONEY, 0)); // This line causes exception
updateHealth(args.getDouble(HEALTH, 0.0));
updateEquipmentMass(args.getDouble(EQUIPMENT_MASS, 0.0));
return parentView;
}
public static StatusBarFragment newInstance(int money, double health, double equipmentMass)
{
StatusBarFragment frag = new StatusBarFragment();
Bundle args = new Bundle();
args.putInt(MONEY, money);
args.putDouble(HEALTH, health);
args.putDouble(EQUIPMENT_MASS, equipmentMass);
frag.setArguments(args);
return frag;
}
}
Strange approach.奇怪的做法。 I think there is a missing connection between args and the data.我认为 args 和数据之间缺少联系。 On newInstance() do this.MONEY = money and the other strings.在 newInstance() 上执行 this.MONEY = money 和其他字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.