Question

I am working on an application, and from a list view I create a bundle that includes the item selected and the previous item. What I need to determine is if the previous item actually gets bundled through. If it exists, I want the information, but if it doesn't exist, then I need to set my text views to reflect that. But I get a null pointer exception if it doesn't exist when trying to load the receiving activity (the bundling activity does not cause the crash as I found during debugging - I get to the point where I'm testing for the data in the bundle before it crashes). So I've included the code from the receiving activity.

    Bundle evmBundle = this.getIntent().getExtras();
    final EVMData evm = (EVMData) evmBundle.getSerializable("evm");

    final Project project = (Project) evmBundle.getSerializable("project");

            if (!evmBundle.getSerializable("prvEVM").equals(null)){
        final EVMData prvEvm = (EVMData) evmBundle.getSerializable("prvEVM");
        edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
        edtPrvAC.setText(prvEvm.getAc().toString());
    }
    else{
        edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
        edtPrvAC.setText("0");
    }

I know something is getting passed through in the bundle for "prvEVM" because it showed up as part of the bundle in the debugger.

I also tried pulling it out of the bundle first and then trying to compare it. After pulling it out of the bundle, prvEvm is null (looking at the variables in the debugger), so I thought something like this might work:

     if (!prvEvm.equals(null)){
        edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
        edtPrvAC.setText(prvEvm.getAc().toString());
    }else{
        edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
        edtPrvAC.setText("0");
    }

But I get a NullPointerException because prvEvm is Null. So I tried flipping the if test around, but got the same results. I should note that no matter how I set this up, if prvEvm is not null, all configurations here work - the requested data is put in the TextView. Basically, I need to be able to get around this null pointer exception. I know the object is null, I want to test for that so that if it is, that object isn't used. It will only be null once.

Était-ce utile?

La solution

Don't use equals(null) as you call a method (equals) on a null object. Instead, compare to null:

if (prvEvm != null){

besides, equals(null) always returns false.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top