Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type cast from Java.Lang.Object to native CLR type in MonoDroid

How to cast Java.Lang.Object to some native type?

Example:

ListView adapter contains instances of native type Message. When i am trying to get SelectedItem from ListView it returns instance of Message type casted to Java.Lang.Object, but I can't find solution to cast Java.Lang.Object back to Message.

var message = (Message)list.SelectedItem;
// throws  Error    5   Cannot convert type 'Java.Lang.Object' to 'Message'

Please Help.

like image 201
mironych Avatar asked Jul 06 '11 09:07

mironych


3 Answers

After long time debuging, have found the solution:

public static class ObjectTypeHelper
{
    public static T Cast<T>(this Java.Lang.Object obj) where T : class
    {
        var propertyInfo = obj.GetType().GetProperty("Instance");
        return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
    }
}

Usage example:

 var message = list.GetItemAtPosition(e.Position).Cast<Message>();
 bundle.PutInt("Message", message.ID);

After careful sdk study have found MonoDroid integrated extension for this purpose:

public static TResult JavaCast<TResult>(this Android.Runtime.IJavaObject instance)
where TResult : class, Android.Runtime.IJavaObject
Member of Android.Runtime.Extensions
like image 55
mironych Avatar answered Nov 03 '22 21:11

mironych


The least magical way of getting a native type from the Spinner is to call

    message = ((ArrayAdapter<Message>)list.Adapter).GetItem(list.SelectedItemPosition);
like image 9
Jon Bates Avatar answered Nov 03 '22 21:11

Jon Bates


I used this code from above answer and it works fine to me

    public static class ObjectTypeHelper
{
    public static T Cast<T>(this Java.Lang.Object obj) where T : class
    {
        var propertyInfo = obj.GetType().GetProperty("Instance");
        return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
    }
}

and this is how I used

var selectedLocation = locationSpinner.SelectedItem.Cast<Location>();

I am able to get my location object fine from spinner

like image 5
devil_coder Avatar answered Nov 03 '22 20:11

devil_coder