Why is Android doing things behind my back?
<p>Or, in other words: what is the context's lifetime in Android?</p>

<p>I'm asking this because I get a <strong>NullPointerException</strong> when trying to access the context in the following code:</p>

<pre><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
    }
}
</code></pre>

<p>Here is the code for the <code>App</code> class:</p>

<pre><code>public class App extends Application {
    private static Context $context;

    @Override
    public void onCreate() {
        App.$context = this;
    }

    public static Context context() {
        return $context;
    }
}
</code></pre>

<p>Why is Android doing things <strong>behind my back</strong>??? When I set a value to a variable I want it to stay <strong>THE SAME</strong> until I <strong>EXPLICITLY</strong> modify it.</p>

<hr>

<h2>EDIT</h2>

<p>Here is the code that calls <code>MyClass</code>:</p>

<pre><code>MyClass mc = new MyClass();
Intent intent = new Intent(App.context(), MyActivity.class);
intent.putExtra("mc", mc);
startActivity(intent);
</code></pre>

<p>then in <code>MyActivity</code>:</p>

<pre><code>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).
}
</code></pre>
