Home >Java >javaTutorial >Why Does My Android App Crash with 'Attempt to invoke virtual method… on a null object reference' When Transitioning Activities?
Attempt to Invoke Virtual Method: Null Object Reference
Issue:
When transitioning from SplashActivity to LoginActivity in an Android application, a crash occurs with the error: "Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference."
Explanation:
The exception occurs because LoginActivity attempts to access views (e.g., EditText, TextView) before the activity is fully initialized and ready. findViewById() is called in LoginActivity's constructor, but setContentView(...) is not explicitly called in onCreate().
Resolution:
To fix the issue, initialize the view fields in onCreate() after setContentView(...):
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); usernameField = (EditText) findViewById(R.id.username); passwordField = (EditText) findViewById(R.id.password); error = (TextView) findViewById(R.id.error); progress = (ProgressBar) findViewById(R.id.progress); }
Optimization Suggestion:
Consider using a Handler instead of a Timer to schedule the intent transition. A Timer runs the TimerTask on a background thread, which should be avoided in this case. The Handler will ensure the task is executed on the UI thread.
new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(SplashActivity.this, LoginActivity.class); startActivity(intent); finish(); } }, 1500);
The above is the detailed content of Why Does My Android App Crash with 'Attempt to invoke virtual method… on a null object reference' When Transitioning Activities?. For more information, please follow other related articles on the PHP Chinese website!