Android 为什么安卓在我背后做事?
或者,换句话说:在Android中,上下文的生命周期是什么 我这样问是因为在尝试访问以下代码中的上下文时,我得到了一个NullPointerException:Android 为什么安卓在我背后做事?,android,Android,或者,换句话说:在Android中,上下文的生命周期是什么 我这样问是因为在尝试访问以下代码中的上下文时,我得到了一个NullPointerException: public class MyClass implements Serializable { private transient Context _context; public MyClass() { _context = App.context(); Log.d("is null:
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
}
}
以下是应用程序
类的代码:
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).
}
试着一开始就这样做
private Context _context = null;
我注意到一件事:在构造函数中
public MyClass() {
_context = App.context();
Log.d("is null: " + (context == null)); // shows false
}
你在哪里查
context == null
但是,该变量称为_context。那么上下文变量(不带u)从何而来 无所谓。。。我发现了我所做的愚蠢:上下文是一个临时成员,当我将其以捆绑方式传递时,它不会被序列化。所以当我把它取出来时,它显然是空的
我知道我应该使用Parcelable而不是Serializable,但这只是一个玩具项目,所以…您可以通过以下方式完成:
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中删除该上下文成员,这不是一个好方法:
public class MyClass implements Serializable {
public void myMethod() {
Toast.makeText(App.getAppContext(), "test", Toast.LENGTH_SHORT).show();
// ^ throws NullPointerException for _context
}
}
不,不工作。。。无论如何,我在构造函数中设置了_上下文,如我的示例所示:它不是null.mmm,我明白了。。。看来有些奇怪的事情发生了。。。但是我感觉示例中缺少了一些代码,试着把所有的东西都放进去,这样我就可以深入研究了。好吧,我认为有两种选择:或者错误在传递“mc”var的过程中(检查它们是否是同一个实例),或者是检索问题。我做过几个安卓应用程序,但我从来没有遇到过这个问题(尽管我总是通过“简单”变量,而不是对象),所以在调用my方法时尝试简化代码?@ThinkStiple:请查看我的编辑。如果您有其他需要我澄清的事情,请询问。您的构造函数中的context==null是否应该在它前面有下划线?对不起,这是一个小错误。正在编辑…似乎您不想序列化上下文,而是希望将对象作为捆绑包的一部分传递。我怀疑这是问题的根源。你能把它去掉并测试一下吗?我强烈认为这就是问题所在。