Tuesday, 12 October 2021

Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?

This code, with the block at the top commented, runs successfully:

public class MainActivity extends AppCompatActivity {

    /*
    EditText username = (EditText)findViewById(R.id.editText_Username);
    EditText password = (EditText)findViewById(R.id.editText_Password);
    TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
    TextView welcome = (TextView)findViewById(R.id.textView_Welcome);
    Button login=(Button)findViewById(R.id.button_Login);
    Button anotherLogin=(Button)findViewById(R.id.button_Login_Another);
    */

    public void doLoginOnClick(View v)
    {
        String s1=username.getText().toString();
        inputdata.setText(s1);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab); 
        fab.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    } 
 
}

I am trying to capture id of component using

findViewById(R.id.***)

as you can see, I put this code in comment at the very beginning of the code.

EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
TextView welcome = (TextView)findViewById(R.id.textView_Welcome);
Button login=(Button)findViewById(R.id.button_Login);
Button anotherLogin=(Button)findViewById(R.id.button_Login_Another);

If I remove the comment above and run it (both in emulator and real device), the program crashes immediately, I am surprised what's wrong here?

even I have tried to initialize the same thing using constructor.

But if I put it inside onCreate() there's no crash? Why?

I was trying to fetch info of username and password and display it to the textview in textView_Inputdata using

EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
inputdata.setText(username.getText.toString()+" "+password.getText.toString());

Is there better or easier way to do that?



from Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?

No comments:

Post a Comment