[英]Launching intent from a class outside an activity
I've got two activities, one of them is called MyActivity
. 我有两个活动,其中一个叫做MyActivity
。 I want both of them to be able to use a function located in a class othat we may call MyClass
. 我希望他们俩能够使用位于我们可能称之为MyClass
的类中的函数。 In MyClass
, I try to use an intent to launch the activity AnotherActivity
. 在MyClass
,我尝试使用intent来启动活动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. 由于构造函数将上下文作为参数,我只是尝试在构造函数中存储活动的上下文,然后在尝试创建我的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: MyActivity
中使用该类的代码如下所示:
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. 但是,即使没有任何参数为null(使用简单的if语句检查), intent
似乎为null并抛出NullPointerException
。 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. 我是Android和Java开发的新手,所以请尽可能地解释它。
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, ie 并且为了确保它的意图是NULL,而不是startActivity方法中的内部,你可以添加一些检查,即
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 --- eg what are you calling startActivity() on in MyClass? 我怀疑有一些剪切和粘贴问题 - 例如你在MyClass中调用startActivity()是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.