Search code examples
androidsortingxamarinibeaconicollection

Xamarin Android - sorting iBeacon iCollection causes exception


I'm trying to sort an iCollection of iBeacon objects, but as soon as the code runs it throws an exception. The code i'm trying to run is as follows. It works fine without any ordering or sorting, but i need to be able to sort the collection on proximity, as shown (with lowest proximity first i.e proximity being equal to 1):

async void RangingBeaconsInRegion(object sender, RangeEventArgs e)
   {

     if (e.Beacons.Count > 0) 
      {
        var orderedBeacons = e.Beacons.OrderBy(b => b.Proximity); //this causes the problem

      foreach (var beacon1 in orderedBeacons) 
       {
          //do all my stuff here on my ordered beacons
       }
    }
}

Here is the exception:

[mono] Unhandled Exception:
[mono] System.ArgumentException: 'jmethod' must not be IntPtr.Zero.
[mono] Parameter name: jmethod
[mono]   at Android.Runtime.JNIEnv.CallObjectMethod (IntPtr jobject, IntPtr jmethod) [0x00000] in <filename unknown>:0 
[mono]   at Android.Runtime.JavaCollection`1[RadiusNetworks.IBeaconAndroid.IBeacon].CopyTo (RadiusNetworks.IBeaconAndroid.IBeacon[] array, Int32 array_index) [0x00000] in <filename unknown>:0 
[mono]   at System.Linq.Enumerable.ToArray[IBeacon] (IEnumerable`1 source) [0x00000] in <filename unknown>:0 
[mono]   at System.Linq.QuickSort`1[RadiusNetworks.IBeaconAndroid.IBeacon]..ctor (IEnumerable`1 source, System.Linq.SortContext`1 context) [0x00000] in <filename unknown>:0 
[mono]   at System.Linq.QuickSort`1+<Sort>c__Iterator0[RadiusNetworks.IBeaconAndroid.IBeacon].MoveNext () [0x00000] in <filename unknown>:0 

Any ideas how i can get the collection ordered correctly please?


Solution

  • This should work for you. Let me know how it goes.

    var allBeacons = new List<Beacon>();
    
    foreach(var b in e.Beacons)
    {
        allBeacons.Add(b);
    }
    
    var orderedBeacons = allBeacons.OrderBy(b => b.Proximity);