Object类方法的空指针异常

时间:2018-04-27 16:07:57

标签: android

我收到一个空指针异常,我的应用程序崩溃了。 我在对象类方法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方法中获得此异常

2 个答案:

答案 0 :(得分:0)

可能是因为您的距离字符串为空,因此您无法将其解析为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
}

答案 1 :(得分:0)

requireNonNull不保证您将获得非null元素。它只是在返回的元素为null时抛出错误。你得到一个null元素,因此你的代码抛出异常。