Skip to content Skip to sidebar Skip to footer

System.invalidcastexception - Works In Debug, Fails At Release

UNHANDLED EXCEPTION: System.InvalidCastException: Cannot cast from source type to destination type. 06-11 19:39:01.690 I/MonoDroid(17577): at MyApp.Inbox.CorrespondenceActivity.C

Solution 1:

The solution was fairly simple. It was the casting at the bottom of the method that resulted in the error

((ISpannable) spanText).RemoveSpan(s);
((ISpannable) spanText).SetSpan(urlSpan, start, end, flags); 

To work around this the method had to be changed to the following:

public ISpanned CorrectLinkPaths(ISpanned spanText)
{
    Object[] spans = spanText.GetSpans(0, spanText.Length(), Class.FromType(typeof (Object)));
    ISpannable spanned = new SpannableString(spanText);
    foreach (var s in spans)
    {
        var start = spanText.GetSpanStart(s);
        var end = spanText.GetSpanEnd(s);
        var flags = spanText.GetSpanFlags(s);

        if (s.GetType() == typeof (URLSpan))
        {
            var urlSpan = (URLSpan)s;
            if (!urlSpan.URL.StartsWith("http"))
            {
                if (urlSpan.URL.StartsWith("/"))
                    urlSpan = new URLSpan("http://www.mydomain.com" + urlSpan.URL);
                else
                    urlSpan = new URLSpan("http://www.mydomain.com/" + urlSpan.URL);
            }
            spanned.RemoveSpan(s);
            spanned.SetSpan(urlSpan, start, end, flags);
        }
    }
    return spanned;
}

Solution 2:

You should use JavaCast, it works in release and debug mode. You will have to include namespace Android.Runtime.

spanText.JavaCast<ISpannable>().RemoveSpan(s);
spanText.JavaCast<ISpannable>().SetSpan(urlSpan, start, end, flags); 

Post a Comment for "System.invalidcastexception - Works In Debug, Fails At Release"