Or, in other words: what is the context’s lifetime in Android?
I’m asking this because I get a NullPointerException when trying to access the context in the following code:
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
}
}
Here is the code for the App class:
public class App extends Application {
private static Context $context;
@Override
public void onCreate() {
App.$context = this;
}
public static Context context() {
return $context;
}
}
Why is Android doing things behind my back??? When I set a value to a variable I want it to stay THE SAME until I EXPLICITLY modify it.
EDIT
Here is the code that calls MyClass:
MyClass mc = new MyClass();
Intent intent = new Intent(App.context(), MyActivity.class);
intent.putExtra("mc", mc);
startActivity(intent);
then in 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).
}
Nevermind… I found the stupidity I did: the Context is a transient member and it doesn’t get serialized when I pass it in a bundle. So when I get it out it will obviously be null.
I know I should use Parcelable instead of Serializable, but this is just a toy project sooo…