我正在尝试在MyActivity
中创建一个片段,并将需要显示的数据传递给它。我目前正在尝试通过静态方法newInstance()
但是,当我打开活动时,尝试在onCreateView()
中打开捆绑包时会收到Null Pointer异常
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String, int)' on a null object reference
这是在第一次调用getInt()
时发生的,这使我认为getArguments()
由于某种原因正在返回空包,而我不知道为什么会返回空包。
MyActivity.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
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;
}
}
答案 0 :(得分:-2)
奇怪的方法。我认为args和数据之间缺少连接。在newInstance()上执行此操作。MONEY= money和其他字符串。