views:

67

answers:

2

I've got two activities, one of them is called MyActivity. I want both of them to be able to use a function located in a class othat we may call MyClass. In MyClass, I try to use an intent to launch the activity AnotherActivity. Since the constructor takes a context as parameter, I simply tried to store a context from the activity in the constructor, and then use it when I try to create my intent.

class MyClass {
  private Context cxt;

  MyClass(Context cxt) {
    this.cxt = cxt;
  }

  startIntent() {
    Intent intent = new Intent(cxt, AnotherActivity.class);
    startActivity(intent); // this line throws a NullPointerException
  }
}

The code in MyActivity to use the class is shown below:

myClassObject = new MyClass(MyActivity.this);
myClassObject.startIntent();

However, even thought none of the arguments are null (checked that with a simple if-statement), intent seems to be null and a NullPointerException is thrown. Why does it not work, and what can I do to solve the problem? I'm quite new to Android and Java development, so please explain it as basic as you can.

+1  A: 
cxt.startActivity(new Intent(cxt, AnotherActivity.class));

and to be sure that it's intent is NULL, and not something internal in startActovity method, you can add some checks, i.e.

Intent intent = new Intent(cxt, AnotherActivity.class);
Log.d(toString(), "intent = " + intent.toString());
cxt.startActivity(intent);
zed_0xff
Nice, now it works as expected! I don't get why the intent should be null before calling startActivity thought, and it doesn't seems like it is when I run my program.
nico
A: 

I've used almost identical code in my applications and it's worked fine.

I suspect there's something else going on that's in code you haven't shown us; I suspect there's some cut-and-paste issues --- e.g. what are you calling startActivity() on in MyClass?

David Given