Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

后端 未结 2 1568
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 03:07

When my SplashActivity opens the LoginActivity my app crashes.

The following is my SplashActivity.java:

packag         


        
相关标签:
2条回答
  • 2020-11-22 03:19

    Views defined in xml file can only be accessed in java code, after setting the ContentView as the required xml file using:

    setContentView(R.layout.xml_file_name);
    

    So 1st call above method inside onCreate method and then initialize the View instances inside onCreate or inside the methods in which the instance will be used.

    0 讨论(0)
  • 2020-11-22 03:30

    An Activity is not fully initialized and ready to look up views until after setContentView(...) is called in onCreate().

    Only declare the fields like the following:

    private EditText usernameField, passwordField;
    private TextView error;
    private ProgressBar progress;
    

    and then assign the values in onCreate:

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

    Might not be part of the problem but as an extra bit of advice a Timer runs the TimerTask on a background thread and that should be avoided in this case. Replace the Timer with a Handler instead to run it 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);
    
    0 讨论(0)
提交回复
热议问题