HashSet Null Pointer Exception in Android but doesn39t occur in java. why

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I was working with hashsets and somehow i came across NPE. I know hashset allow null values. So i tried to know what exactly happening and i created following code in java(just for learning purpose)

Java Code -

public class numbers {
static HashSet<String> s = new HashSet<>();

    public static void main(String[] args) {
        s.add("a");
        s.add(null);
        s.add("b");
        for(String l:s)
        {
            System.out.println(l);
        }
    }
}

It gave me no exceptions. The output is printed to the console. Then i tried to run the same code in android

Android Code -

public class MainActivity extends Activity {
    HashSet<String> s = new HashSet<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        s.add("a");
        s.add(null);
        s.add("b");

        for(String l:s)
        {
            //System.out.println(l);
            Log.i("ExceptionCheck", l);
        }
    }
}

Now when i run the application . Null pointer exception is raised at Log statement, where i am trying to read the output.

Can anyone explain me whats the difference ?

Answers

You have added a null to your set and then you re printing the values.

http://androidxref.com/4.4.4_r1/xref/frameworks/base/core/jni/android_util_Log.cpp#108 http://androidxref.com/4.4.4_r1/xref/frameworks/base/core/jni/android_util_Log.cpp#108

However, something like this works that ensures the message is not null:

Log.i("ExceptionCheck", "" + l);

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/25159785/hashset-null-pointer-exception-in-android-but-doesnt-occur-in-java-why

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils