嘗試將上下文從MainActivity類傳遞到另一個時遇到問題。這是ContextPasser類。如何將MainActivity的上下文傳遞給Android中的另一個類?
public class ContextPasser extends Application{
public Context context;
public ContextPasser(){
context = getApplicationContext();
}}
但是,如果使用上下文變量中的其他類,像這樣:
Line line = new Line(new ContextPasser().context);
我得到一個空指針異常。我想得到一個不涉及傳入上下文變量的解決方案,因爲我查看了所有其他stackoverflows,並且他們似乎沒有幫助我。一,我找到了解決辦法是:
Context context;
MyHelperClass(Context context){
this.context=context;
}
這並不能幫助我,因爲我打電話Line類是,
Line line = new Line(new ContextPasser().context);
另一類稱爲GameRunner像這樣:
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類自身的參數。
請讓我知道任何建議或答案。 我真的很感激它。 非常感謝您的時間和考慮!
活動有自己的上下文,爲什麼你不使用Line line = new Line(this); – Aryan
我的回答對你有幫助嗎? – OBX