NullPointerException with findViewById in variable definition

社会主义新天地 提交于 2021-02-05 11:30:06

问题


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


回答1:


You need to call findViewById after calling setContentView in onCreate



来源:https://stackoverflow.com/questions/60159198/nullpointerexception-with-findviewbyid-in-variable-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!