或者,换句话说:Android中的上下文生命周期是什么?
我问这个是因为我在尝试访问以下代码中的上下文时遇到 NullPointerException :
public class MyClass implements Serializable {
private transient Context _context;
public MyClass() {
_context = App.context();
Log.d("is null: " + (_context == null)); // shows false
}
// other code (that doesn't touch context in any way)
public void myMethod() {
Log.d("is null: " + (_context == null)); // shows true!!!
// WHY?!? for the love of God, WHY?!?
// It was already initialized in the constructor!!!
Log.d("is null: " + (App.context() == null)); // shows false
Toast.makeText(_context, "test", Toast.LENGTH_SHORT).show();
// ^ throws NullPointerException for _context
}
}
以下是App
类的代码:
public class App extends Application {
private static Context $context;
@Override
public void onCreate() {
App.$context = this;
}
public static Context context() {
return $context;
}
}
为什么Android背后的事情背后 ???当我将值设置为变量时,我希望它保持相同,直到我明确修改它。
以下是调用MyClass
的代码:
MyClass mc = new MyClass();
Intent intent = new Intent(App.context(), MyActivity.class);
intent.putExtra("mc", mc);
startActivity(intent);
然后在MyActivity
:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
Bundle bundle = getIntent().getExtras();
MyClass mc = (MyClass) bundle.get("mc");
mc.myMethod(); // here it crashes, see previous code (before editing).
}
答案 0 :(得分:0)
一开始就尝试这样做。
private Context _context = null;
答案 1 :(得分:0)
我注意到一件事:在构造函数中你有
public MyClass() {
_context = App.context();
Log.d("is null: " + (context == null)); // shows false
}
你在哪里检查
context == null
然而,该变量被称为_context。那么上下文变量(没有_)来自哪里?
答案 2 :(得分:0)
没关系......我发现我做的愚蠢:当我在捆绑中传递它时,上下文是一个临时成员而它没有被序列化。所以当我把它拿出来时显然会为空。
我知道我应该使用Parcelable而不是Serializable,但这只是一个玩具项目... ...
答案 3 :(得分:0)
您可以通过以下方式执行此操作:
public class App extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
App.context=getApplicationContext();
}
public static Context getAppContext() {
return context;
}
}
因此,您可以从应用程序的任何位置拨打App.getAppContext()
。
从MyClass中删除Context成员,这不是一个好方法:
public class MyClass implements Serializable {
public void myMethod() {
Toast.makeText(App.getAppContext(), "test", Toast.LENGTH_SHORT).show();
// ^ throws NullPointerException for _context
}
}