1

I want sort my custom list based on field. My list has around 125 records as it is static.

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

But, on calling above code just after adding all objects in list. I am getting below error.

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)
VVB
  • 6,526
  • 7
  • 39
  • 71

1 Answers1

2

Add null checks before comparing:

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());
    }
});