将字符串与null进行比较时显示异常

时间:2013-12-29 17:30:51

标签: java android

我在比较String变量时显示空指针异常的应用程序是null或不是

我的错误堆栈跟踪如下

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.appovative.poi/com.appovative.places.SinglePlaceDetails}:       java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3687)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NullPointerException
    at com.appovative.places.SinglePlaceDetails.onCreate(SinglePlaceDetails.java:73)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)

我在onCreate()方法中的代码

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.single_place_map);



    Intent intent = getIntent();
    PlaceLocation placeLoc = (PlaceLocation) intent
            .getSerializableExtra("Place");

    double lat = placeLoc.getLat();
    double lng = placeLoc.getLng();
    title = placeLoc.getTitle();
    vicinity = placeLoc.getVic();

    if(title.toString().length() != 0 && vicinity.toString().length()!= 0)
    {
        sbMsg.append(title.toString()).append("\n").append(vicinity.toString());
    }
    else if(!title.equalsIgnoreCase("null") && vicinity.equalsIgnoreCase("null")){
        sbMsg.append(title);
    }
}

我在if(condition)中得到空指针异常。

4 个答案:

答案 0 :(得分:3)

避免使用toString(),只需进行空检查

if(title != null && vicinity != null)
{
    tv.setText(title+ "\n"+vicinity);
}

还要确保已分配“tv”。

答案 1 :(得分:1)

    if(title != null && vicinity != null)
    {
        if (tv != null) {
            tv.setText(title+ "\n"+vicinity);
        }
    }

您必须确保tv变量不为null。它可能会导致NullPointer异常,因为您必须为其设置文本。

答案 2 :(得分:0)

使用string!= null而不是string.equalsIgnoreCase

答案 3 :(得分:0)

因为您无法在null上使用方法,首先应检查该对象是否为空。

例如:

if(title != null && vicinity != null && tv != null)
{
  tv.setText(title+ "\n"+vicinity);
}