Android: "Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference"
When navigating from SplashActivity to LoginActivity, the app crashes with the error "Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference." This error typically occurs when accessing views or performing UI-related actions before the Activity is fully initialized.
In this case, the error is most likely caused by the following issue:
Premature initialization of view fields:
In LoginActivity.java, the usernameField, passwordField, error, and progress fields are declared and assigned values in the constructor. However, the Activity's onCreate() method has not yet been called when these fields are accessed, meaning that setContentView() has not been executed and the view hierarchy has not been set up. Consequently, the fields are attempting to refer to non-existent views, resulting in the null pointer exception.
Resolution:
To resolve the issue, it is necessary to initialize the view fields only after setContentView() has been called. This ensures that the view hierarchy is fully initialized and accessible.
The updated code in LoginActivity.java:
private EditText usernameField; private EditText passwordField; private TextView error; private ProgressBar progress; @Override 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); }
Additionally, it is recommended to use a Handler instead of a Timer to control the navigation from SplashActivity to LoginActivity to ensure that it occurs on the UI thread.
The updated code in SplashActivity.java:
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 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference' During Activity Navigation?. For more information, please follow other related articles on the PHP Chinese website!