Android Studio 按钮导致崩溃

Posted

技术标签:

【中文标题】Android Studio 按钮导致崩溃【英文标题】:Android Studio Button Causing Crash 【发布时间】:2020-03-05 10:53:36 【问题描述】:

在应用程序中,我单击了一个链接,该链接应将我带到注册页面。应用程序最终崩溃,我在运行日志中收到以下错误。

错误消息 - 已更新

E/androidRuntime: FATAL EXCEPTION: main
Process: com.alanlyne.tbm, PID: 17423
java.lang.RuntimeException: Unable to start activity ComponentInfocom.alanlyne.tbm/com.alanlyne.tbm.SignUpActivity: 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.alanlyne.tbm.SignUpActivity.onCreate(SignUpActivity.java:37)
    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)
    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) 

导致错误的代码 

   package com.alanlyne.tbm;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;

public class SignUpActivity extends AppCompatActivity 
    public EditText emailId, password;
    Button btnSignUp;
    TextView tvSignIn;
    FirebaseAuth mFirebaseAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mFirebaseAuth = FirebaseAuth.getInstance();
        emailId = findViewById(R.id.editText);
        password = findViewById(R.id.editText2);
        btnSignUp = findViewById(R.id.button2);
        tvSignIn = findViewById(R.id.textView);
        btnSignUp.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                String email = emailId.getText().toString();
                String pwd = password.getText().toString();
                if (email.isEmpty()) 
                    emailId.setError("Please enter email");
                    emailId.requestFocus();
                 else if (pwd.isEmpty()) 
                    password.setError("Please enter password");
                    password.requestFocus();
                 else if (email.isEmpty() && pwd.isEmpty()) 
                    Toast.makeText(SignUpActivity.this, "Fields are empty!", Toast.LENGTH_SHORT).show();
                 else if (!(email.isEmpty() && pwd.isEmpty())) 
                    mFirebaseAuth.createUserWithEmailAndPassword(email, pwd).addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() 
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) 
                            if (!task.isSuccessful()) 
                                Toast.makeText(SignUpActivity.this, "Sign Up Unsuccessful, Please Try Again", Toast.LENGTH_SHORT).show();
                             else 
                                startActivity(new Intent(SignUpActivity.this, HomeActivity.class));
                            
                        
                    );
                 else 
                    Toast.makeText(SignUpActivity.this, "Error Occurred!", Toast.LENGTH_SHORT).show();
                
            
        );

        tvSignIn.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Intent i = new Intent(SignUpActivity.this, loginActivity.class);
                startActivity(i);
            
        );
    

我还附上了注册活动的 XML 页面,以防可能导致问题。

按钮的 XML - 已更新

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context=".SignUpActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_
        android:layout_
        android:layout_marginStart="85dp"
        android:layout_marginLeft="85dp"
        android:layout_marginTop="231dp"
        android:layout_marginEnd="85dp"
        android:layout_marginRight="85dp"
        android:layout_marginBottom="569dp"
        android:ems="10"
        android:hint="Email"
        android:inputType="textEmailAddress"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText2"
        android:layout_
        android:layout_
        android:layout_marginStart="85dp"
        android:layout_marginLeft="85dp"
        android:layout_marginEnd="85dp"
        android:layout_marginRight="85dp"
        android:layout_marginBottom="8dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.505"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText"
        app:layout_constraintVertical_bias="0.074" />

    <TextView
        android:id="@+id/textView"
        android:layout_
        android:layout_
        android:layout_marginStart="177dp"
        android:layout_marginLeft="177dp"
        android:layout_marginTop="340dp"
        android:layout_marginEnd="177dp"
        android:layout_marginRight="177dp"
        android:layout_marginBottom="97dp"
        android:text="Already have an account? Sign in here"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

    <Button
        android:id="@+id/signUp"
        android:layout_
        android:layout_
        android:layout_marginTop="66dp"
        android:layout_marginBottom="226dp"
        android:text="Sign Up"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

    <TextView
        android:id="@+id/textView3"
        android:layout_
        android:layout_
        android:layout_marginStart="176dp"
        android:layout_marginLeft="176dp"
        android:layout_marginTop="99dp"
        android:layout_marginEnd="178dp"
        android:layout_marginRight="178dp"
        android:layout_marginBottom="102dp"
        android:text="Sign Up"
        app:layout_constraintBottom_toTopOf="@+id/editText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

上一个活动的代码

package com.alanlyne.tbm;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class loginActivity extends AppCompatActivity 
    public EditText emailId, password;
    Button btnSignIn;
    TextView tvSignUp;
    FirebaseAuth mFirebaseAuth;
    private FirebaseAuth.AuthStateListener mAuthStateListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mFirebaseAuth = FirebaseAuth.getInstance();
        emailId = findViewById(R.id.editText);
        password = findViewById(R.id. editText2);
        btnSignIn = findViewById(R.id.button2);
        tvSignUp = findViewById(R.id.textView);

        mAuthStateListener = new FirebaseAuth.AuthStateListener() 
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) 
                FirebaseUser mFirebaseUser = mFirebaseAuth.getCurrentUser();
                if(mFirebaseUser != null)
                    Toast.makeText(loginActivity.this, "You are logged in", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent(loginActivity.this, HomeActivity.class);
                    startActivity(i);
                
                else
                    Toast.makeText(loginActivity.this, "Please login", Toast.LENGTH_SHORT).show();
                
            
        ;
        btnSignIn.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 

                String email = emailId.getText().toString();
                String pwd = password.getText().toString();
                if (email.isEmpty()) 
                    emailId.setError("Please enter email");
                    emailId.requestFocus();
                 else if (pwd.isEmpty()) 
                    password.setError("Please enter password");
                    password.requestFocus();
                 else if (email.isEmpty() && pwd.isEmpty()) 
                    Toast.makeText(loginActivity.this, "Fields are empty!", Toast.LENGTH_SHORT).show();
                 else if (!(email.isEmpty() && pwd.isEmpty())) 
                    mFirebaseAuth.signInWithEmailAndPassword(email, pwd).addOnCompleteListener(loginActivity.this, new OnCompleteListener<AuthResult>() 
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) 
                            if(!task.isSuccessful())
                                Toast.makeText(loginActivity.this, "Login Error, Please Try Again", Toast.LENGTH_SHORT).show();
                            else
                                Intent intToHome = new Intent(loginActivity.this,HomeActivity.class);
                                startActivity(intToHome);
                            
                        
                    );

                 else 
                    Toast.makeText(loginActivity.this, "Error Occurred!", Toast.LENGTH_SHORT).show();
                

            
        );
        tvSignUp.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Intent intSignUp = new Intent(loginActivity.this, SignUpActivity.class);
                startActivity(intSignUp);
            
        );
    

    @Override
    protected void onStart() 
        super.onStart();
        mFirebaseAuth.addAuthStateListener(mAuthStateListener);
    

上一个活动的 XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context=".loginActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_
        android:layout_
        android:layout_marginStart="85dp"
        android:layout_marginLeft="85dp"
        android:layout_marginTop="231dp"
        android:layout_marginEnd="85dp"
        android:layout_marginRight="85dp"
        android:layout_marginBottom="569dp"
        android:ems="10"
        android:hint="Email"
        android:inputType="textEmailAddress"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText2"
        android:layout_
        android:layout_
        android:layout_marginStart="85dp"
        android:layout_marginLeft="85dp"
        android:layout_marginEnd="85dp"
        android:layout_marginRight="85dp"
        android:layout_marginBottom="8dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.505"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText"
        app:layout_constraintVertical_bias="0.074" />

    <TextView
        android:id="@+id/textView"
        android:layout_
        android:layout_
        android:layout_marginStart="177dp"
        android:layout_marginLeft="177dp"
        android:layout_marginTop="340dp"
        android:layout_marginEnd="177dp"
        android:layout_marginRight="177dp"
        android:layout_marginBottom="97dp"
        android:text="Not registered? Sign up here"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

    <Button
        android:id="@+id/button2"
        android:layout_
        android:layout_
        android:layout_marginTop="66dp"
        android:layout_marginBottom="226dp"
        android:hint="Sign in"
        android:text="Sign in"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText2"
        app:layout_constraintVertical_bias="0.384" />

    <TextView
        android:id="@+id/textView3"
        android:layout_
        android:layout_
        android:layout_marginStart="176dp"
        android:layout_marginLeft="176dp"
        android:layout_marginTop="99dp"
        android:layout_marginEnd="178dp"
        android:layout_marginRight="178dp"
        android:layout_marginBottom="102dp"
        android:text="Sign In"
        app:layout_constraintBottom_toTopOf="@+id/editText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

btnSignUp = findViewById(R.id.button2); 出于某种原因返回 null,这可能是几件事。您可以先尝试将其转换为按钮吗? btnSignUp= (Button)findViewById(R.id.button2) 没看可悲,类似的错误。 好的,所以在你的onCreate中,你将contentView设置为R.layout.activity_main,你还有其他布局吗?试试你的注册活动布局,而不是主要的 点击btnSignUp时应用会崩溃吗? 当您移动代码时,您对旧 xml id 的引用似乎没有更新。您的注册按钮应该是 R.id.signUp 而不是 button2 【参考方案1】:

您对Button 的引用在内部是错误的 SignUpActivity 活动。

使用

btnSignUp = findViewById(R.id.signUp);

代替

btnSignUp = findViewById(R.id.button2);

【讨论】:

以上是关于Android Studio 按钮导致崩溃的主要内容,如果未能解决你的问题,请参考以下文章

使画布视图无效时单击按钮后应用程序崩溃(Android Studio,Java)

通过移动设备在 Android Studio 中单击 TextView 会导致应用程序崩溃 [关闭]

onClick按钮导致Android崩溃

android studio中片段内的RecyclerView使我的应用程序崩溃

android studio模拟器:单击面板按钮会导致模拟器关闭

启动 Unity 时应用程序崩溃 - 在 Android Studio 中测试时不会崩溃