当我在微调器上选择项目时,出现NullPointerException

I have two spinners, one with a list of countries(countrySpinner) and the other with a list of provinces(stateSpinner). I want the stateSpinner to be active only if Nigeria is selected on the countrySpinner, and for the other countries on to be selectable without selecting item on the stateSpinner. My code seam to work when I select Nigerian on the countrySpinner and a corresponding state, but I GET THIS NullPointerException : println needs a message, anytime I select a country other than Nigeria on the countrySpinner. Not quite sure of what to do to get pass here. I Would appreciate any help. My code below.enter code here

public class RegisterActivity extends AppCompatActivity {

    Spinner countrySpinner, stateSpinner;
    List<String> countryList;
    ArrayList<String> stateList;
    ArrayAdapter<String> stateAdapter;
    String countrySelected, stateSelected, gender;
    TextInputLayout name, email, password, confirmPw;
    RadioGroup genderOptionGroup;
    RadioButton genderOptionBtn;
    TextView countryUnCheckedWarning;
    Button nextButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);nextButton = findViewById(R.id.createAccNext);

        countryUnCheckedWarning = findViewById(R.id.countrySelectW);

        genderOptionGroup = findViewById(R.id.gender_group);

        name = findViewById(R.id.fullNameInputLayout);
        email = findViewById(R.id.emailInputLayout);
        password = findViewById(R.id.pwInputLayout);
        confirmPw = findViewById(R.id.cpwInputLayout);

        countrySpinner = findViewById(R.id.countryDropDown);
        stateSpinner = findViewById(R.id.stateDropDown);

        stateList = new ArrayList<String>(Arrays.asList("Select State of Residence", "Abia", "Abuja", "Adamawa", "Akwa Ibom", "Anambra",
                "Bauchi", "Bayelsa", "Benue", "Borno", "Cross River", "Delta", "Ebonyi", "Enugu", "Edo",
                "Ekiti", "Gombe", "Imo", "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara",
                "Lagos", "Nasarawa", "Niger", "Ogun", "Ondo", "Osun", "Oyo", "Plateau", "Rivers", "Sokoto",
                "Taraba", "Yobe", "Zamfara", "Territory"));

        stateAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stateList);
        stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        stateSpinner.setAdapter(stateAdapter);

        countryList = new ArrayList<String>();

        countryList.add(0, "Select Country");
        countryList.add("Gambia");
        countryList.add("Sierra Leone");
        countryList.add("Liberia");
        countryList.add("Ghana");
        countryList.add("Nigeria");
        countryList.add("South Africa");

        ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countryList);
        countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        countrySpinner.setAdapter(countryAdapter);

        // Country Spinner

        countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {



                    if (!(parent.getItemAtPosition(position).equals("Nigeria")) && !(parent.getItemAtPosition(position).equals("Select Country"))){
                        // Country other than Nigeria has been selected
                        countrySelected = parent.getItemAtPosition(position).toString();
                        Log.i("Country Selected is",countrySelected);
                        nextButton.setEnabled(true);
                        nextButton.setBackgroundColor(getResources().getColor(R.color.red));

                    }else if (parent.getItemAtPosition(position).equals("Nigeria")){
                        // Nigeria is selected
                        stateSpinner.setAlpha(1);
                        countrySelected = "Nigeria";
                        nextButton.setEnabled(false);
                        nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));

                    }else {

                        countrySelected = "";
                        nextButton.setEnabled(false);
                        nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));
                    }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // State SpinnerGroup

        stateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if (parent.getItemAtPosition(position).equals("Select State of Residence")) {

                    nextButton.setEnabled(false);
                    nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));

                } else {

                    stateSelected = parent.getItemAtPosition(position).toString();
                    nextButton.setEnabled(true);
                    nextButton.setBackgroundColor(getResources().getColor(R.color.red));
                    Log.i("State Selected", stateSelected);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {


            }
        });

    }

    // Name, Email and Password Validation MTDs Below

    private boolean validateName() {

        String nameInpute = name.getEditText().getText().toString().trim();
        // check for non empty field
        if (nameInpute.isEmpty()) {

            name.setError("Name Field Can't be empty");
            return false;

        } else if (nameInpute.length() < 5) {

            name.setError("Name is too short");
            return false;
        } else {

            name.setError(null);
            return true;
        }
    }

    private boolean validateEmail() {

        String emailInpute = email.getEditText().getText().toString().trim();
        // Now we check for non empty field
        if (emailInpute.isEmpty()) {

            email.setError("E-mail Field Can't be empty");
            return false;

        } else if (!Patterns.EMAIL_ADDRESS.matcher(emailInpute).matches()) {

            email.setError("Please enter a valid email address");
            return false;

        } else {
            // Remove Error and return true
            email.setError(null);
            return true;
        }
    }

    private boolean validatePassword() {

        String passwordInpute = password.getEditText().getText().toString().trim();
        // check for non empty field
        if (passwordInpute.isEmpty()) {

            password.setError("Password Field Can't be empty");
            return false;

        } else if (passwordInpute.length() > 15) {

            password.setError("Password is too long");
            return false;
        } else {

            password.setError(null);
            return true;
        }
    }

    private boolean validateCPassword() {

        String passwordInpute = password.getEditText().getText().toString().trim();
        String confirmPWInpute = confirmPw.getEditText().getText().toString().trim();
        // check for non empty field
        if (confirmPWInpute.isEmpty()) {

            confirmPw.setError("Password Field Can't be empty");
            return false;

        } else if (!confirmPWInpute.equals(passwordInpute)) {

            confirmPw.setError("Password does not match");
            return false;
        } else {

            password.setError(null);
            return true;
        }
    }


    public void moveToNextOnReg(View view) {
        // check for or validations

        if (!validateName() | !validateEmail() | !validatePassword() | !validateCPassword()) {
            return; }


        // put whatever result needed here
        String fullName = name.getEditText().getText().toString().trim();
        String emailRegistered = email.getEditText().getText().toString().trim();
        String passwordRegistered = password.getEditText().getText().toString().trim();

        Log.i("Name", fullName);
        Log.i("E-mail", emailRegistered);
        Log.i("Password", passwordRegistered);
        Log.i("Country", countrySelected);
        Log.i("State", stateSelected);
        Log.i("Sex", gender);

        Intent intentNext = new Intent(getApplicationContext(),ToNextActivity.class);
        startActivity(intentNext);

    }

    public void backToOnboarding(View view) {

        Intent intent = new Intent(getApplicationContext(), OnboardingActivity.class);
        startActivity(intent);
        finish();
    }

    public void onGenderSelected(View view){

        int radioId = genderOptionGroup.getCheckedRadioButtonId();
        genderOptionBtn = findViewById(radioId);
        gender = genderOptionBtn.getText().toString();
        Log.i("Gender Selceted", genderOptionBtn.getText().toString());


    }

}


评论
  • nerror
    nerror 回复

    You don't seem to initialize nextButton in onCreate():

     @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);nextButton = findViewById(R.id.createAccNext);
    
        countryUnCheckedWarning = findViewById(R.id.countrySelectW);
    
        genderOptionGroup = findViewById(R.id.gender_group);
    
        name = findViewById(R.id.fullNameInputLayout);
        email = findViewById(R.id.emailInputLayout);
        password = findViewById(R.id.pwInputLayout);
        confirmPw = findViewById(R.id.cpwInputLayout);
    
        countrySpinner = findViewById(R.id.countryDropDown);
        stateSpinner = findViewById(R.id.stateDropDown);
    
        //here.....
        nextButton = findViewById(...............);//what ever the id is in xml