且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

变量定义中带有 findViewById 的 NullPointerException

更新时间:2023-11-19 12:34:22

onCreate中调用setContentView后需要调用findViewById>

I have read the immensely popular thread about Null Point Exceptions but I'm still confused about why I'm getting the error. I am attempting to make sure some EditText's are filled out. I have tried it in the onCreate method and it still doesnt work. Any help would be appreciated. I apologize if this is some stupid question.

public class MainActivity extends AppCompatActivity implements View.OnClickListener { 

EditText scoutName = (EditText) findViewById(R.id.editSN);
EditText teamNumber = (EditText) findViewById(R.id.editTN);
EditText matchNumber = (EditText) findViewById(R.id.editMatchNumber);

@Override
protected void onCreate(Bundle savedInstanceState) {
    stringBuilder = new StringBuilder();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

Button submit = findViewById(R.id.submit);
    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (fieldsOK) {
                openActivity2();
            }
            else {
                System.out.println("You have Missing Forms");
            }
        }
    });
}


private boolean validate(EditText[] fields){
    for(int i = 0; i < fields.length; i++){
        EditText currentField = fields[i];
        if(currentField.getText().toString().length() <= 0){
            return false;
        }
    }
    return true;
}

boolean fieldsOK = validate(new EditText[] { scoutName, teamNumber, matchNumber });

error

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.scoutingapp3250/com.example.scoutingapp3250.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference

The error comes on the the scoutName on above the onCreate method

You need to call findViewById after calling setContentView in onCreate