-2

the app crashes and dont even open and give the error java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

package com.example.andriod.hostelapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        }


    EditText userId = (EditText) findViewById(R.id.user_name);
    EditText userPassword = (EditText) findViewById(R.id.password);

    public void login()
    {
        if (userId.getText().toString().equals("ritwik7101") && 
            userPassword.getText().toString().equals("ritwik123"))

        {
        }
        else{
            Toast.makeText(this, "INCORRECT USERNAME OR PASSWORD!",
                    Toast.LENGTH_LONG).show();
       }
    }
}
DamCx
  • 1,047
  • 1
  • 11
  • 25

2 Answers2

1

You have to put the findViewById calls inside the onCreate method and after the setContent call.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

The attributes are instantiated (invocation of the find.. method) at the time when your class is instantiated, so before the layout is set. Because of this, the elements you want to find are not existing yet.

Here is the same question, including an answer to it: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

Ehler
  • 285
  • 3
  • 11