Avada Kedavra Avada Kedavra -4 years ago 61
Android Question

Unable to set listener for button-Error: Virtual Method

I am making the Login Fragment and also validating it but it generates me an error :

Process: com.shopkart.theinvincible.shopkart, PID: 5477
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference at
com.shopkart.theinvincible.shopkart.LogIn.onCreateView(LogIn.java:46)


This is Login Fragment in which i have inserted the button but it shows an error at the button clickListener in which i declared a Function :

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_log_in, container, false);
LoginEmailId = (EditText) container.findViewById(R.id.login_emailId);
LoginPassword = (EditText) container.findViewById(R.id.login_password);
LoginButton = (Button) container.findViewById(R.id.login_button);
LoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Register();
})};
return view;
}

private void Register() {
intialize();

if (!LogInFail()) {
Toast.makeText(getActivity(), "LogIn Failed! || Try Again", Toast.LENGTH_SHORT).show();
} else {
LogInOk(); } }

private void LogInOk() { }

private boolean LogInFail() {
boolean validation = true;
if (EmailId.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(EmailId).matches()) {
LoginEmailId.setError("Enter Valid Email-Id");
validation = false;
}
if (Password.isEmpty()) {
LoginPassword.setError("Enter Valid Password");
validation = false;
}
return validation;
}

private void intialize() {
EmailId = LoginEmailId.getText().toString().trim();
Password = LoginPassword.getText().toString().trim(); }

Answer Source

you are adding the fields in container and returning view, Replace container with view

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_log_in, container, false);
    LoginEmailId = (EditText) view.findViewById(R.id.login_emailId);
    LoginPassword = (EditText) view.findViewById(R.id.login_password);
    LoginButton = (Button) view.findViewById(R.id.login_button);
    LoginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Register(); 
        })};
   return view;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download