NullPointerException: Attempting to Retrieve Callback fromUninitialized Window
When navigating from SplashActivity to LoginActivity, the app encounters an error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
This error indicates that LoginActivity is trying to access a view component before it has been properly initialized.
Cause
The specific cause of the error lies in the LoginActivity.java code, where the class members are initialized before setContentView() is called in onCreate(). This leads to a situation where the views do not exist yet when the class members try to find them.
Solution
To fix the issue, declare the view members in the class without initialization:
private EditText usernameField, passwordField; private TextView error; private ProgressBar progress;
Then, initialize the members within onCreate() after setContentView() has been called:
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); }
Additional Advice
While not directly related to the error, it is recommended to replace Timer with Handler when running a task 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 Am I Getting a NullPointerException When Accessing Views in My LoginActivity?. For more information, please follow other related articles on the PHP Chinese website!