开发者

Launching intent from a class outside an activity

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 开发者_JS百科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.


cxt.startActivity(new Intent(cxt, AnotherActivity.class));

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

Intent intent = new Intent(cxt, AnotherActivity.class);
Log.d(toString(), "intent = " + intent.toString());
cxt.startActivity(intent);


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜