skip to Main Content

I am writing an application in which you need to log in, and then go to another page. I enter the data into the fields, click the log in button and the transition to another page does not occur. The application crashes

I use the firebase database in the application

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        loginemail = (EditText) findViewById(R.id.email);
        loginpassword = (EditText) findViewById(R.id.password);
        generatorBtn = (Button) findViewById(R.id.idBtnGenerator);
        RegistrationBtn = (Button) findViewById(R.id.register);

        generatorBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!validateEmail() | !validatePassword()) {
                    return;
                }     else if(validateEmail() && validatePassword()) {
                    checkUser();
                } else {
                    Toast.makeText(getApplicationContext(), "Успешно", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent(ActivityLogin.this, GeneratorQRcodeActivity.class);
                    startActivity(i);
                }

            }
        });


        RegistrationBtn.setOnClickListener(new View.OnClickListener() {
             @Override
            public void onClick(View v) {
                Intent i = new Intent(ActivityLogin.this, 
RegistrationActivity.class);
                startActivity(i);
            }
        });

    }

    public Boolean validateEmail() {
        String val = loginemail.getText().toString();
        if (val.isEmpty()) {
            loginemail.setError("Адрес электронной почты не заполнен");
            return false;
        } else {
            loginemail.setError(null);
            return true;
        }
    }

    public Boolean validatePassword() {
        String val = loginpassword.getText().toString();
        if (val.isEmpty()) {
            loginpassword.setError("Пароль не заполнен");
            return false;
        } else {
            loginpassword.setError(null);
            return true;
        }
    }

    public void checkUser() {
        String userLoginEmail = 
loginemail.getText().toString().trim();
        String userPassword = loginpassword.getText().toString().trim();

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
        Query checkUserDatabase = reference.orderByChild("email").equalTo(userLoginEmail);

        checkUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    loginemail.setError(null);
                    String passwordFromDB = snapshot.child(userLoginEmail).child("password").getValue(String.class);

                    if (!Objects.equals(passwordFromDB, userPassword)) {
                        loginemail.setError(null);
                    } else {
                        loginpassword.setError("Недопустимая форма учетной записи");
                        loginpassword.requestFocus();
                    }
                } else {
                    loginemail.setError("Пользователь не существует");
                    loginemail.requestFocus();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

 }

I tried different loop transformations, the application crashes anyway

generatorBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!validateEmail() | !validatePassword()) {
                    return;
                }     else if(validateEmail() && validatePassword()) {
                    checkUser();
                } else {
                    Toast.makeText(getApplicationContext(), "Успешно", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent(ActivityLogin.this, GeneratorQRcodeActivity.class);
                    startActivity(i);
                }

            }
        });

The error is in this block, but I don’t understand why

logcat:
2024-03-12 15:10:56.877 1699-7807 WindowManager system_server E win=Window{e2fc2f4 u0 com.example.scannerandgenerator/com.example.scannerandgenerator.RegistrationActivity} destroySurfaces: appStopped=true cleanupOnResume=false win.mWindowRemovalAllowed=false win.mRemoveOnExit=false win.mViewVisibility=8 caller=com.android.server.wm.ActivityRecord.destroySurfaces:6862 com.android.server.wm.ActivityRecord.destroySurfaces:6843 com.android.server.wm.ActivityRecord.activityStopped:7510 com.android.server.wm.ActivityClientController.activityStopped:310 android.app.I

2

Answers


  1. You have to first connect your project to the Firebase project and then

    Enable Email/Password in Authentication Section

    enter image description here

    Use the below code for the LOGIN through Firebase. (change below code with requirements)

    private void loginUser(String email, String password) {
        auth.signInWithEmailAndPassword(email , password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()){
    
                    DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(auth.getCurrentUser().getUid());
                    reference.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            UserInformation user2=snapshot.getValue(UserInformation.class);
                            String key=snapshot.getKey();
    
                            SharedPreferences preferences=getApplication().getSharedPreferences("prefrence2",MODE_PRIVATE);
                            SharedPreferences.Editor editor=preferences.edit();
                            editor.putBoolean("login",true);
                            editor.putString("user_name",user2.getName());
                            editor.putString("email_login",email);
                            editor.putString("password_login",password);
                            editor.putString("user_Id",auth.getCurrentUser().getUid());
                            editor.commit();
    
                            Intent intent = new Intent(Login_Activity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
    
                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {
    
                        }
                    });
                }
                else {
                    Toast.makeText(Login_Activity.this, "Email or Password not found!  orn " +
                            "Internet Connection not Available", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    

    Register Code

    private void registerUser1(String email, String password, String name) {
    
        auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
    
                    //Here I get UID of User from Firebase Authentication
                    FirebaseUser user = auth.getCurrentUser();
                    String userId = user.getUid();
    
                    //Here User data pushed to Firebase Realtime database
                    DatabaseReference firebaseDataPush = FirebaseDatabase.getInstance().getReference("Users").child(userId);
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", name);
    
                    firebaseDataPush.setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                Toast.makeText(SignUpActivity.this, "Register User Successful!", Toast.LENGTH_SHORT).show();
    
                                Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
                                startActivity(intent);
                                finish();
    
                            } else {
                                Toast.makeText(SignUpActivity.this, "Registration Failed!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
        });
    }
    

    UserInformation.java

    public class UserInformation {
        private String name;
    
        public UserInformation() {
        }
    
        public UserInformation(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return
                    "name='" + name + '''
                    ;
        }
    }
    
    Login or Signup to reply.
  2. There’s a logical issue in your condition check. Instead of |, you should be using || to perform logical OR operation. | is a bitwise OR operator, which evaluates both sides of the expression regardless of the result of the first condition, potentially leading to unexpected behavior. This might be the cause of your app crashing.

    Please replace it inside generatorBtn.setOnClickListener

    Here’s the corrected condition:

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

    Make sure you update all occurrences of this incorrect logical operator in your code. After making this change, try running your app again and see if the crash persists. If it does, you may need to provide more information or debug further to pinpoint the exact cause of the crash.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search