Xamarin Android Class Not Found Exception

The Class Not Found Exception is commonly raised when the class loader tries to find an activity or a broadcast receiver class listed on the app manifest, but it fails to find it. Common examples can be a splash activity with no layout to show an animation, or a broadcast receiver which should load after intent is received, like boot completed intent.

What is common on these cases is that these classes should be configured on the AndroidManifest.xml file as part of the build process, but during the application load lifecycle, these classes are not found. This indicates that there is missing metadata which affects the load process. Let’s review a common application manifest and class declaration and discuss the problem and solution.


<manifest package="com.ozkary.app"
                <action android:name="android.intent.action.BOOT_COMPLETED" />  


On the abbreviated manifest above, we can find the package name and the receiver class.  The receiver class name is relative to the package name which means that during the load time, the class loader will attempt to find a class with the name of com.ozkary.app.BootReceiver.

When the class not found exception is raised, we need to take a look at how our project metadata is getting created. This is where our class attributes become very important for our builds.

Class Metadata with Attributes

During the class implementation phase, we can leverage class attributes to add metadata information to our projects. For a Xamarin Android project, this is very important because this is the metadata that is added to the AndroidManifest file during the build cycle. With that knowledge in mind, let’s take a look at how we should properly declare our class.

[BroadcastReceiver(Name = "com.ozkary.BootReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class BootReceiver : BroadcastReceiver

By looking at our abbreviated class declaration, we are setting the receiver class name properly as well as the intent. When we build the project, the metadata generated from our classes is merged with the Properties/AndroidManifest.xml file.  This is true for all classes including activities.

When encountering this Class Not Found Exception, we should review the content of the manifest file as well our class declarations, and we should find that there is probably not enough metadata added to the classes to prevent this error.

I hope this helps some of you with this problem.

Originally published by ozkary.com


Post a Comment

What do you think?