简体   繁体   中英

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. I'm currently trying to pack all the data in a bundle through the static method newInstance()

When I open the activity however, I get a Null Pointer Exception when I try and unpack the bundle in 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.

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;
    }
}

Strange approach. I think there is a missing connection between args and the data. On newInstance() do this.MONEY = money and the other strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM