我已经创建了一个单独的类来启动和意图,因为我想要从一个线程启动意图,并且不会从活动继承并且不会启动startActivity。每次启动应用程序时,我都会获得上下文的空指针异常。
public class ToLaunch extends Activity {
public void launchScoreloop() {
con.getApplicationContext();
startActivity(new Intent(this, LeaderboardsScreenActivity.class));
}
}
答案 0 :(得分:1)
您正在撰写活动,但未覆盖方法onCreate()
。
public class ToLaunch extends Activity {
@override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Call your method here after a button click cor example or something else
}
public void launchScoreloop() {
con.getApplicationContext();
startActivity(new Intent(this, LeaderboardsScreenActivity.class));
}
}
参考这两个关于使用Intent启动另一个Activity的教程: tuto 1 tuto 2
如果你想从另一个类启动Activity,你应该将上下文传递给第二个类,如下所示:
SecondClass instance = new SecondClass(this);
,你的SecondClass的构造函数将是这样的:
public void SecondClass(Context _context){
this.context = _context;
}
然后您可以使用传递给SecondClass的上下文来启动Avtivity,如下所示:
this.context.startActivity(....);
答案 1 :(得分:0)
如果thread是您活动中的内部类,您可以使用
startActivity(new Intent(YourActivity.this, LeaderboardsScreenActivity.class));
If it is a separate class you can make a constructor that take context has constructor as argument and you can pass your activity context into that constructor
Context con;
public YourThread(Context context){
con = context;
}
并从您的活动内部开始,同时制作线程对象
YourThread thread = new YourThread(this);