开发者

Cannot get context to launch intent

I've made a separate class to launch and intent as the class I would like to launch the intent from is a thread and does not inherit from activity and would not launch startActivity. Every time I launch the app I get a null pointer exception for the context.

public class ToLaunch extends Activity 开发者_Go百科{
    public void launchScoreloop() {
        con.getApplicationContext();
        startActivity(new Intent(this, LeaderboardsScreenActivity.class));
    }
}


You Are writing an Activity , and you didn't override the method 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));
    }
}

refer this two tutorials about using intents to start another Activity : tuto 1 tuto 2

And if you want to launch the Activity from another Class , you should pass the context to the second Class like this :

SecondClass instance = new SecondClass(this);

and the contructor of your SecondClass will be something like this :

public void SecondClass(Context _context){
   this.context = _context;
}

and then you can start the Avtivity by using the context that you passed to your SecondClass like this :

this.context.startActivity(....);


If thread is a inner class inside your activity you can use

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

and from inside your activity, while making thread object

    YourThread thread = new YourThread(this);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜