排序自定义对象列表时出现NullPointerException

时间:2017-09-20 08:06:01

标签: java android arraylist

我希望根据字段对自定义列表进行排序。我的列表有大约125条记录,因为它是静态的。

Collections.sort(receivedSOSModelArrayList, new Comparator<ReceivedSOSModel>() {
    @Override
    public int compare(ReceivedSOSModel receivedSOSModel, ReceivedSOSModel t1) {
        return receivedSOSModel.getReceivedSOSFrom().compareTo(t1.getReceivedSOSFrom());
    }
});

但是,在添加列表中的所有对象之后调用上面的代码。我收到了以下错误。

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.compareTo(java.lang.String)' on a null object reference
    at com.xx.xx.Activities.sos.SOSReceivedActivity$4.compare(SOSReceivedActivity.java:366)
    at com.xx.xx.Activities.sos.SOSReceivedActivity$4.compare(SOSReceivedActivity.java:355)
    at java.util.TimSort.binarySort(TimSort.java:261)
    at java.util.TimSort.sort(TimSort.java:204)
    at java.util.Arrays.sort(Arrays.java:1998)
    at java.util.Collections.sort(Collections.java:1900)
    at com.xx.xx.Activities.sos.SOSReceivedActivity.compareList(SOSReceivedActivity.java:355)
    at com.xx.xx.Activities.sos.SOSReceivedActivity.loadDataToRecyclerView(SOSReceivedActivity.java:318)
    at com.xx.xx.Activities.sos.SOSReceivedActivity.access$100(SOSReceivedActivity.java:44)
    at com.xx.xx.Activities.sos.SOSReceivedActivity$1.onDataChange(SOSReceivedActivity.java:126)
    at com.google.android.gms.internal.zzakg.zza(Unknown Source)
    at com.google.android.gms.internal.zzalg.zzcxk(Unknown Source)
    at com.google.android.gms.internal.zzalj$1.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:746)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

1 个答案:

答案 0 :(得分:1)

在比较之前添加空检查:

Collections.sort(receivedSOSModelArrayList, new Comparator<ReceivedSOSModel>() {
    @Override
    public int compare(ReceivedSOSModel receivedSOSModel, ReceivedSOSModel t1) {
        if (receivedSOSModel == null || receivedSOSModel.getReceivedSOSFrom() == null) {
            Log.v("first", "NULL");
            return -1;  //null values will be displayed at bottom in sorted list
        }

        if (t1 == null || t1.getReceivedSOSFrom() == null ) {
            Log.v("second", "NULL");
            return 1;  //null values will be displayed at bottom in sorted list
        }

        return receivedSOSModel.getReceivedSOSFrom().compareTo(t1.getReceivedSOSFrom());
    }
});