Launching intent from a class outside an activity

2019-02-10 15:58发布

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.

2条回答
▲ chillily
2楼-- · 2019-02-10 16:28
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);
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-10 16:45

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?

查看更多
登录 后发表回答