ToolbarItemBadgeSample
ToolbarItemBadgeSample copied to clipboard
Object reference is null in android
Hello
i am getting "Object reference not set to an instance of an object" on var toolbar = CrossCurrentActivity.Current.Activity.FindViewById(Resource.Id.toolbar) as Android.Support.V7.Widget.Toolbar; line in the ToolbarItemBadgeService service class for android. it works fine in IOS.
Have you added [assembly: Dependency(typeof(ToolbarItemBadgeService))] in ToolbarItemBadgeService class both Android and iOS above namspace
@lijusparkt I've added that but this issue still happens to me
Tengo el mismo problema
Hi all, I found that this is the problem of the Plugin.CurrentActivity The CrossCurrentActivity.Current.Activity is null, hence causing the NullReferenceException.
So we need to obtain the Activity object for it to work properly. To do so, in the ToolbarItemBadgeService.cs
using Android.Content;
using Android.App;
public class ToolbarItemBadgeService : IToolbarItemBadgeService
{
static Context _context;
public static void Init (Context context)
{
_context = context;
}
public void SetBadge(Page page,ToolbarItem item, string value,Color backgroundColor,Color textColor)
{
Device.BeginInvokeOnMainThread(() =>
{
var activity = _context as Activity;
var toolbar = activity.FindViewById(Resource.Id.toolbar) as Android.Support.V7.Widget.Toolbar;
.
.
.
BadgeDrawable.SetBadgeText(_context, menuItem, value, backgroundColor.ToAndroid(), textColor.ToAndroid());
And we need to provide the context for ToolbarItemBadgeService when the app launches. And this is a good habit for Android dependency service modules.
In the MainActivity.cs, put ToolbarItemBadgeService.Init(this);
at the beginning of the OnCreate Method
public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
ToolbarItemBadgeService.Init(this);
base.OnCreate(bundle);
}
}