1

I use Xamarin with Monogame and i need run android activity from c# code. I try do this:

public class Test : Activity

{

public void Start()
{
  StartActivity(typeof(MyActivity));
}

}

}

Then from Update() i calling Start().

protected override void Update(GameTime gameTime)
{ 
   ...
   Test test = new Test();
   test.Start();
   ...
}

But i have error. Help me, please

detrous
  • 46
  • 5
  • Post the complete error message that you are recieving. – user2339071 Jul 09 '15 at 15:12
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Ben N Jul 09 '15 at 15:15

1 Answers1

2

An existing Activity instance has a bit of work that goes on behind the scenes when it's constructed; activities started through the intent system (all activities) will have a Context reference added to them when they are instantiated. This context reference is used in the call-chain of StartActivity.

So, the Java.Lang.NullPointerException seen after invoking StartActivity on your Test activity instance is because the Context inside that instance has never been set. By using the new operator to create an activity instance you've circumvented the normal way activities are instantiated, leaving your instance in an invalid state!

This can be fixed by using the global application context to launch the activity:

var intent = new Intent(Android.App.Application.Context, typeof(Test));
intent.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity (intent);
matthewrdev
  • 11,930
  • 5
  • 52
  • 64