Developing application in C# .Net 4.5 using Xamarin, targeting Android. I have a custom class that has some properties in it. I am trying to use a built in component that does comparison using Java.Util.IComparator and Java.Lang.Object. Because it is a built in component, I don't have much flexibility into changing those two items.
My custom class is named recBatch and inside of it, I have some properties of integers and strings.
This is where the component gets initialized. It basically calls a method each time the user clicks on the header for column 0.
tableView.SetColumnComparator(0, GetBatchIdComparator());
This is the method that gets called by the component
public Java.Util.IComparator GetBatchIdComparator()
{
return new BatchIdComparator();
}
And finally, here is the class that is returned by the call.
public class BatchIdComparator : Java.Lang.Object, Java.Util.IComparator
{
public int Compare(Java.Lang.Object lhs, Java.Lang.Object rhs)
{
var leftID = (recBatch)lhs;
var rightID = (recBatch)rhs;
return leftID.Batch.CompareTo(rightID.Batch);
}
}
The first thing I tried to do above by just casting gives me an error as seen here. I did try what Visual Studio is suggesting but could not get it working either.
The next thing I tried was to create a new class like this one and change the cast from recBatch, my actual class to this new class to do the casting:
public class BatchIdComparator : Java.Lang.Object, Java.Util.IComparator
{
public int Compare(Java.Lang.Object lhs, Java.Lang.Object rhs)
{
var leftID = (castClass)lhs;
var rightID = (castClass)rhs;
return leftID.BatchData.Batch.CompareTo(rightID.BatchData.Batch);
}
}
public class castClass : Java.Lang.Object
{
public castClass(recBatch batchData)
{
batchData = BatchData;
}
public recBatch BatchData { get; private set; }
}
With this, I don't have errors and can compile but the problem is I am getting a cast exception when I run. The code does compile and because I am casting, I do have access to one of the properties in recBatch (Batch or recBatch.Batch). However, again, I get a cast exception. The exact error is:
So basically, I just need to cast the Java.Lang.Object into recBatch but I guess I am doing it wrong. Everything is "wired up" properly because if I put a break point at the Compare method, it does hit and the lhs, rhs arguments that are passed in have my class data in them (ie Batch) even though they are Java.Lang.Object types.
Any help is appreciated!
Thanks!
Copyright License:
Author:「Michael Bedford」,Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.
Link to:https://stackoverflow.com/questions/37956507/type-cast-java-object-to-my-class