Home > Java > javaTutorial > Why Do I Get 'Attempt to Invoke Virtual Method 'android.view.Window$Callback android.view.Window.getCallback()' on a Null Object Reference' in Android?

Why Do I Get 'Attempt to Invoke Virtual Method 'android.view.Window$Callback android.view.Window.getCallback()' on a Null Object Reference' in Android?

Barbara Streisand
Release: 2024-12-09 14:10:15
Original
1023 people have browsed it

Why Do I Get

“Attempt to Invoke Virtual Method 'android.view.Window$Callback android.view.Window.getCallback()' on a Null Object Reference” in Android

This error occurs when an Activity attempts to access views before it has been fully initialized. Specifically, the error is triggered when the Window.getCallback() method is called on a null object, which can happen if the setContentView() method has not yet been invoked in onCreate().

Cause:
To prevent this error, it is important to declare view fields without initializing them in the class declaration:

private EditText usernameField, passwordField;
private TextView error;
private ProgressBar progress;
Copy after login

Then, assign values to these fields within onCreate() after setContentView() has been called:

@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);
}
Copy after login

Additional Advice:

  • Consider using a Handler to run code on the UI thread instead of a Timer, as Timers execute tasks on a background thread.
new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
}, 1500);
Copy after login

The above is the detailed content of Why Do I Get 'Attempt to Invoke Virtual Method 'android.view.Window$Callback android.view.Window.getCallback()' on a Null Object Reference' in Android?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template