问题
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);
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;
}
This does not help me because I am calling the Line class which is,
Line line = new Line(new ContextPasser().context);
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();
}
}
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!
回答1:
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);
回答2:
OBX's answer shows one way to do it. But you should understand why your approach does not work.
Instances of Android components such as Application
and Activity
are not fully realized as Context
s until they've been initialized by the framework. This happens sometime before onCreate(...)
is called. If you create a new
instance yourself, it won't be initialized and will neither have nor be usable as a Context
. For the same reason, calling getApplicationContext()
in a field assignment or constructor will return null
or throw an exception.
MyActivity extends Activity {
private Context appContext = getApplicationContext(); // wrong
public MyActivity {
appContext = getApplicationContext(); // wrong
}
public void onCreate(final Bundle savedInstanceState) {
appContext = getApplicationContext(); // correct
}
}
来源:https://stackoverflow.com/questions/42036278/how-to-pass-context-from-mainactivity-to-another-class-in-android