как исправить: приложение постоянно останавливается android студия - PullRequest
0 голосов
/ 25 марта 2020

Я занимаюсь разработкой приложения, которое содержит страницу входа и регистрации. Он содержит домашнюю страницу, откуда пользователь может перейти на страницу регистрации или входа. Моя страница регистрации работает нормально, но когда я нажимаю кнопку входа на главной странице, приложение закрывается.

Пожалуйста, посмотрите на мой acttivity_login. xml файл, я не смог добавьте его как фрагмент кода.

ниже приведен код java для начала действия

package com.cuboid.chatapp;

publi c начало класса расширяет AppCompatActivity {

private Button loginBtn, signupBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);

    loginBtn = (Button) findViewById(R.id.start_login);
    signupBtn = (Button) findViewById(R.id.start_signup);

    loginBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(start.this, login.class));
            finish();
        }
    });

    signupBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(start.this, signup.class));
            finish();
        }
    });
}

}

Ниже приведен код моего логина. java

package com.cuboid.chatapp;

publi c class логин расширяет AppCompatActivity {

private EditText inputEmail, inputPassword;
public  String email;
public String password;
private Button login_btn, forgotPassword_btn;
private FirebaseAuth auth;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    auth = FirebaseAuth.getInstance();
    if (auth.getCurrentUser() != null)
    {
        startActivity(new Intent(login.this, contentChoice.class));
        finish();
    }
    setContentView(R.layout.activity_login);

    inputEmail = (EditText) findViewById(R.id.login_email);
    inputPassword = (EditText) findViewById(R.id.login_password);
    login_btn = (Button) findViewById(R.id.login_btn);
    forgotPassword_btn = (Button) findViewById(R.id.login_forgot_pwd);

    auth = FirebaseAuth.getInstance();
    login_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            email = inputEmail.getText().toString();
            password = inputPassword.getText().toString();
            if (TextUtils.isEmpty(email))
            {
                Toast.makeText(getApplicationContext(), "Enter an email ", Toast.LENGTH_SHORT).show();
                return;
            }
            else if (TextUtils.isEmpty(password))
            {
                Toast.makeText(getApplicationContext(), "Enter password", Toast.LENGTH_SHORT).show();
                return;
            }
            loginUser();
        }
    });


}
public void  loginUser()
{
   auth.signInWithEmailAndPassword(email, password)
           .addOnCompleteListener(login.this, new OnCompleteListener<AuthResult>() {
               @Override
               public void onComplete(@NonNull Task<AuthResult> task) {
                    if (!task.isSuccessful())
                    {
                       Toast.makeText(login.this, "Authentication failed", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        Intent intent = new Intent(login.this, contentChoice.class);
                        startActivity(intent);
                        finish();
                    }
               }
           });
}

}

Ниже приведена ошибка Logcat.

-03-25 17:12:44.060 11688-11688/com.cuboid.chatapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cuboid.chatapp, PID: 11688
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cuboid.chatapp/com.cuboid.chatapp.login}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.cuboid.chatapp.login.onCreate(login.java:44)
    at android.app.Activity.performCreate(Activity.java:7136)
    at android.app.Activity.performCreate(Activity.java:7127)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)

Понятия не имею, что это за ошибка это все о. Кто-нибудь, пожалуйста, помогите. Заранее спасибо.

1 Ответ

0 голосов
/ 25 марта 2020

В сообщении об ошибке говорится, что одно из этих назначений вернуло значение null:

loginBtn = (Button) findViewById(R.id.start_login);
signupBtn = (Button) findViewById(R.id.start_signup);

Это означает, что представление с переданным идентификатором не было найдено в макете. Вам нужно будет выяснить, какое представление вы действительно хотели найти, и использовать правильный идентификатор.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...