繁体   English   中英

对象类方法上的空指针异常

[英]Null pointer exception on Object class method

我收到一个空指针异常,我的应用程序崩溃了。 我在我的对象类方法getDistance()中得到了空指针异常,并且我无法弄清为什么我得到了错误

在这段代码中,我得到了异常

private void readData() {
    DatabaseReference databaseReference;
    databaseReference = FirebaseDatabase.getInstance().getReference();

    databaseReference.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
          //  Toast.makeText(getApplicationContext(), "child added!", 
Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            //Toast.makeText(getApplicationContext(),"value 
//changed",Toast.LENGTH_SHORT).show();

            double distance = 0;

            for (DataSnapshot messageSnapshot : 
dataSnapshot.getChildren()) {
                SensorModel sensorModel = 
dataSnapshot.getValue(SensorModel.class);
                distance = 
Double.parseDouble(Objects.requireNonNull(sensorModel).getDistance());

                if (distance < 10 )
                {
                    NotificationManager notificationManager = 
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                    Notification notification = new 
NotificationCompat.Builder(getApplicationContext())
                            .setContentTitle(AppConstant.ALERT)

.setContentText(AppConstant.INTRUDER_DETECTED)

.setSmallIcon(android.R.drawable.stat_sys_warning)
                    .setSound(Uri.parse("android.resource://"
                            + getPackageName() + "/" + 
R.raw.intruder_alert))

                            .build();
                    notificationManager.notify(1, notification);
                }

        }

我的SensorModel.java

public class SensorModel {
private long date;
private long time;
private long humidity;
private String motion;
private String distance;
private String temperature;



public SensorModel(){

}
public SensorModel(long date, String distance, long humidity, String 
motion, String temperature, long time){
    this.distance=distance;
    this.date =date;
    this.motion = motion;
    this.temperature = temperature;
    this.humidity = humidity;
    this.time = time;
}

public long getDate() {
    return date;
}

public void setDate(long date) {
    this.date = date;
}

public long getTime() {
    return time;
}

public void setTime(long time) {
    this.time = time;
}

public long getHumidity() {
    return humidity;
}

public void setHumidity(long humidity) {
    this.humidity = humidity;
}

public String getMotion() {
    return motion;
}

public void setMotion(String motion) {
    this.motion = motion;
}

public String getDistance() {
    return distance;
}

public void setDistance(String distance) {
    this.distance = distance;
}

public String getTemperature() {
    return temperature;
}

public void setTemperature(String temperature) {
    this.temperature = temperature;
}
}

Logcat

java.lang.NullPointerException: Attempt to invoke virtual method 
'java.lang.String java.lang.String.trim()' on a null object reference
    at java.lang.StringToReal.parseDouble(StringToReal.java:263)
    at java.lang.Double.parseDouble(Double.java:301)
    at excel.com.sensordetector.service.IntruderDetectionService$1.
onChildChanged(IntruderDetectionService.java:63)
    at com.google.android.gms.internal.firebase_database.zzbt.zza(Unknown 
Source)
    at com.google.android.gms.internal.firebase_database.zzgx.
zzdr(Unknown Source)
    at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown 
Source)
    at android.os.Handler.handleCallback(Handler.java:742)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5615)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.
run(ZygoteInit.java:774)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)

请告诉我为什么我在readData方法中得到此异常

可能是因为您的距离字符串为空,所以您将无法将其解析为Double。

您为什么不简单检查一下呢?

采用:

if (distance != null && distance != 0) { }

如果要在解析后检查它。

但是使用:

if (distance != null && !distance.isEmpty()) { }

如果要在解析之前检查字符串。

让我知道是否有帮助。


更新:

尝试这个:

public String getDistance() {

    if (distance == null || distance.isEmpty()) {
        return "0"; // we return 0 by default if we have nothing else to return
    }
    return distance; // else, we simply return the distance
}

requireNonNull不能保证您将获得一个非null的元素。 当返回的元素为null时,它只会引发错误。 您将得到一个null元素,因此您的代码将引发异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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