getting "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener)' on a null object reference"

huangapple go评论77阅读模式
英文:

getting "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener)' on a null object reference"

问题

I was trying to make firebase authentication but for some reason this button is giving a NullPointerException, I checked the button name and I cant find why it is throwing such error

Logcat:

     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.anan.login.MainActivity.onCreate(MainActivity.java:45)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409);
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83);
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135);
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95);
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016);
        at android.os.Handler.dispatchMessage(Handler.java:107);
        at android.os.Looper.loop(Looper.java:214);
        at android.app.ActivityThread.main(ActivityThread.java:7356);
        at java.lang.reflect.Method.invoke(Native Method);
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492);
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930);

Main.java:

public class MainActivity extends AppCompatActivity {
    EditText mEmail,mPassword;
    Button mButton; // This button is causing the NullPointerException
    TextView Login;
    FirebaseAuth fAuth;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mEmail = findViewById(R.id.Email);
        mPassword = findViewById(R.id.Password);
        mButton = findViewById(R.id.button); // You need to uncomment this line to initialize the button
        progressBar = findViewById(R.id.progressBar);
        fAuth = FirebaseAuth.getInstance();

        if (fAuth.getCurrentUser() != null){
            startActivity(new Intent(getApplicationContext(),Main2Activity.class));
            finish();
        }

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String Email = mEmail.getText().toString().trim();
                String password = mPassword.getText().toString().trim();

                progressBar.setVisibility(View.VISIBLE);
                // Register user in Firebase
                fAuth.createUserWithEmailAndPassword(Email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){
                            Toast.makeText(MainActivity.this, "Register Successful", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(getApplicationContext(),Main2Activity.class));
                        }else{
                            Toast.makeText(MainActivity.this, "Register failed", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }
}

Main.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_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/Email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Email"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.52"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.25" />

    <EditText
        android:id="@+id/Password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Password"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.52"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/imageView"
        app:layout_constraintVertical_bias="0.405" />

    <Button
        android:id="@+id/button"
        android:layout_width="79dp"
        android:layout_height="52dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Please note that you should uncomment the line that initializes the mButton in your MainActivity.java file to fix the NullPointerException issue.

英文:

I was trying to make firebase authentication but for some reason this button is giving a NullPointerException, I checked the button name and I cant find why it is throwing such error

the code and the Logcat are included below

Logcat:

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method &#39;void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)&#39; on a null object reference
at com.anan.login.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)&#160;
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)&#160;
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)&#160;
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)&#160;
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)&#160;
at android.os.Handler.dispatchMessage(Handler.java:107)&#160;
at android.os.Looper.loop(Looper.java:214)&#160;
at android.app.ActivityThread.main(ActivityThread.java:7356)&#160;
at java.lang.reflect.Method.invoke(Native Method)&#160;
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)&#160;
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)&#160;

Main.java:

public class MainActivity extends AppCompatActivity {
EditText mEmail,mPassword;
Button mButton;
TextView Login;
FirebaseAuth fAuth;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEmail = findViewById(R.id.Email);
mPassword = findViewById((R.id.Password));
//mButton = findViewById(R.id.button);
progressBar = findViewById(R.id.progressBar);
fAuth = FirebaseAuth.getInstance();
if (fAuth.getCurrentUser() != null){
startActivity(new Intent(getApplicationContext(),Main2Activity.class));
finish();
}
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
progressBar.setVisibility(View.VISIBLE);
//Register user in Firebase
fAuth.createUserWithEmailAndPassword(Email,password).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
@Override
public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
if (task.isSuccessful()){
Toast.makeText(MainActivity.this, &quot;Register Successful&quot;, Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Main2Activity.class));
}else{
Toast.makeText(MainActivity.this, &quot;Register failed&quot;, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}

Main.xml:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
tools:context=&quot;.MainActivity&quot;&gt;
&lt;EditText
android:id=&quot;@+id/Email&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:ems=&quot;10&quot;
android:inputType=&quot;textPersonName&quot;
android:text=&quot;Email&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintHorizontal_bias=&quot;0.52&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;
app:layout_constraintVertical_bias=&quot;0.25&quot; /&gt;
&lt;EditText
android:id=&quot;@+id/Password&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:ems=&quot;10&quot;
android:inputType=&quot;textPersonName&quot;
android:text=&quot;Password&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintHorizontal_bias=&quot;0.52&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;@+id/imageView&quot;
app:layout_constraintVertical_bias=&quot;0.405&quot; /&gt;
&lt;Button
android:id=&quot;@+id/button&quot;
android:layout_width=&quot;79dp&quot;
android:layout_height=&quot;52dp&quot;
android:text=&quot;Button&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

...............................................................................................................

答案1

得分: 1

你从未给 mButton 赋值。你有一个被注释掉的赋值语句:

//mButton = findViewById(R.id.button);

如果你不给它一个实际在你的视图层次结构中的视图赋值,它将保持默认值 null。

另外,我注意到你从未填充过你的布局。你根本没有任何可用的视图。

英文:

You never assigned a value to mButton. You have an assignment commented out:

        //mButton = findViewById(R.id.button);

If you don't assign it a value which is an actual View in your view hierarchy, it's going to retain the default value of null.

Also, I'm noticing that you never inflated your layout. You simply don't have any views to work with at all.

答案2

得分: 0

将视图绑定到您的活动,然后访问其小部件

super.onCreate(savedInstanceState);之后,在onCreate(..)方法内添加以下行:

setContentView(R.layout.main);
英文:

Bind view to your activity before accessing its widget

Add below line just after super.onCreate(savedInstanceState); inside onCreate(..) method

   setContentView(R.layout.main);

答案3

得分: 0

  1. 你没有在你的 onCreate 方法中指定布局,因此你的主活动没有布局可供膨胀。

  2. 你没有在你的 onCreate 方法中为 mButton 赋值,因此它被自动赋值为 null。

请将你的 onCreate 代码替换为以下内容:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);                   // 指定你的布局
    mEmail = findViewById(R.id.Email);
    mPassword = findViewById(R.id.Password);
    mButton = findViewById(R.id.button);             // 从你的布局中为 mButton 赋值
    progressBar = findViewById(R.id.progressBar);
    fAuth = FirebaseAuth.getInstance();

    if (fAuth.getCurrentUser() != null) {
        startActivity(new Intent(getApplicationContext(), Main2Activity.class));
        finish();
    }
}
英文:
  1. You did not specify the layout in your onCreate method so your main activity has no layout to inflate

  2. You did not assign a value to mButton in your onCreate method so it is authomatically assigned null.

Replace your onCreate code with the following:

    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);                   //Specify your layout
mEmail = findViewById(R.id.Email);
mPassword = findViewById((R.id.Password));
mButton = findViewById(R.id.button);             //Assign a value to mButton from your layout
progressBar = findViewById(R.id.progressBar);
fAuth = FirebaseAuth.getInstance();
if (fAuth.getCurrentUser() != null){
startActivity(new Intent(getApplicationContext(),Main2Activity.class));
finish();
}
}

huangapple
  • 本文由 发表于 2020年8月4日 02:39:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63235112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定