如何将上下文从MainActivity传递到Android中的另一个类? [英] How to pass context from MainActivity to another class in Android?

查看:249
本文介绍了如何将上下文从MainActivity传递到Android中的另一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将上下文从MainActivity类传递到另一个时遇到问题.这是ContextPasser类.

I am experiencing an issue when trying to pass the context from the MainActivity class to another. Here is the ContextPasser Class.

public class ContextPasser extends Application{
public Context context;
public ContextPasser(){
    context = getApplicationContext();
}}

但是,如果我在另一个类中使用上下文变量,就像这样:

But if I use the context variable in the other class, like this:

Line line = new Line(new ContextPasser().context);

我收到一个空指针异常.我想得到一个不涉及传递上下文变量的解决方案,因为我已经查看了所有其他stackoverflows,它们似乎并没有帮助我.我找到的解决方案之一是:

I am getting a null pointer exception. I want to get a solution which does not involve passing in a context variable because I have looked at all of the other stackoverflows and they do not seem to help me with that. One of the solutions that I found was:

Context context;
MyHelperClass(Context context){
this.context=context;
}

这对我没有帮助,因为我正在调用Line类,

This does not help me because I am calling the Line class which is,

Line line = new Line(new ContextPasser().context);

在另一个称为GameRunner的类中,如下所示:

in another class called the GameRunner like so:

public class GameRunner extends Activity {
Line line = new Line(new ContextPasser().context);
public void draw(Canvas canvas){
    line.draw(canvas);
    getWindow().getDecorView().setBackgroundColor(Color.BLACK);
}

public void update(){
    line.update();
}

}

因此,我想创建一个将通过Context而不接受Context类本身的参数的方法.

So, I want to create a method that will pass the Context without accepting parameters of the Context class themselves.

请让我知道任何建议或答案. 我真的很感激. 非常感谢您的时间和考虑!

Please let me know any suggestions or answers. I would really appreciate it. Thanks a lot for your time and consideration!

推荐答案

如果您的其他班级是非活动班级,这就是您通过Context的方式:

If your other class is a non-activity class this is how you pass the Context:

public class MyNonActivityClass{

// variable to hold context
private Context context;

//save the context received via constructor in a local variable

public MyNonActivityClass(Context context){
    this.context=context;
}

}

这就是您传递上下文的方式:

And this is how you pass the context :

MyNonActivityClass mClass = new MyNonActivityClass(this);

这篇关于如何将上下文从MainActivity传递到Android中的另一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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