问题
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