从类启动意图的活动外 [英] Launching intent from a class outside an activity

查看:95
本文介绍了从类启动意图的活动外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个活动,其中之一叫 MyActivity 。我想他们两个人能够使用位于类othat,我们可以调用一个函数 MyClass的。在 MyClass的,我尝试使用意图启动活动 AnotherActivity 。由于构造函数的上下文为参数,我只是试图从存储在构造活动背景下,然后用它当我尝试创建我的意图。

  MyClass类{
  私人语境CXT;

  MyClass的(语境CXT){
    this.cxt = CXT;
  }

  startIntent(){
    意向意图=新的意图(CXT,AnotherActivity.class);
    startActivity(意向); //此行抛出一个NullPointerException异常
  }
}
 

MyActivity 的code使用类如下所示:

  myClassObject =新MyClass的(MyActivity.this);
myClassObject.startIntent();
 

不过,甚至认为没有一个参数为空(检查过用一个简单的if语句),意图似乎是空和 NullPointerException异常被抛出。为什么它不工作,我能做些什么来解决这个问题? 我是很新的Andr​​oid和Java开发,所以请解释一下基本就可以。

解决方案

  cxt.startActivity(新意图(CXT,AnotherActivity.class));
 

和,以确保它的目的是NULL,而不是内部的startActivity方法,你可以添加一些检查,如

 意向意图=新的意图(CXT,AnotherActivity.class);
Log.d(的toString(),意图=+ intent.toString());
cxt.startActivity(意向);
 

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.

解决方案

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);

这篇关于从类启动意图的活动外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆