ToolbarItemBadgeSample icon indicating copy to clipboard operation
ToolbarItemBadgeSample copied to clipboard

Object reference is null in android

Open shahshraddha2 opened this issue 5 years ago • 4 comments

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.

shahshraddha2 avatar Dec 12 '19 20:12 shahshraddha2

Have you added [assembly: Dependency(typeof(ToolbarItemBadgeService))] in ToolbarItemBadgeService class both Android and iOS above namspace

lijusparkt avatar Mar 13 '20 07:03 lijusparkt

@lijusparkt I've added that but this issue still happens to me

image

Ruvi1996 avatar Apr 07 '20 17:04 Ruvi1996

Tengo el mismo problema

DarlingSanchez avatar May 09 '20 04:05 DarlingSanchez

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);
    }
}

AlvinKwong avatar Aug 05 '20 06:08 AlvinKwong