Forum Xamarin.Android

Getting NullReferenceException on MainActivity in BroadcastReceiver onReceive method.

Hi,
I been battling to solve this issue. I am trying to use Mainactivity method inside onReceive method. But I am keep getting System.NullReferenceException: Object reference not set to an instance of an object.
Here is my code,

[BroadcastReceiver (Name = "pioneer.pioneer.incomingControllerSer.ControllerServBroadCast", Exported =true, Enabled =true)]
public class ControllerServBroadCast : BroadcastReceiver
{
    public ControllerServBroadCast()
    {

    }
    MainActivity ma;

    public ControllerServBroadCast(MainActivity MainActivity)
    {
        this.ma = MainActivity;
    }
    private const string ModeSender= "pioneer.pioneer.ModeSender";
    public override void OnReceive(Context context, Intent intent)
    {
        switch (intent.Action)
        {
            case ModeSender:
                string mode = intent.GetStringExtra("Mode");
                Toast.MakeText(context, mode, ToastLength.Short).Show();
                //if(ma!=null)
                ma.onActivate(mode);
                break;
            default:
                break;
        }

    }
}

Inside mainacitivity ,

CSBroadcastReceiver = new ControllerServBroadCast(this);

            LocalBroadcastManager.GetInstance(this).RegisterReceiver(CSBroadcastReceiver, new IntentFilter("pioneer.poineer.ModeSender"));

Posts

  • mrizwanmrizwan Member ✭✭

    I solved it by creating an instance of mainactivity

    MainActivity.mainActivityInstance = this;

    and onreceive method,

    MainActivity.mainActivityInstance.onActivate(mode);

Sign In or Register to comment.