0

I am new to Android Application Development and while working on a project. I receive the following error and I can't seem to figure out the solution and it makes my application crash.

I have a application which is conneting to firebase and registering user and saving its details to the database. But when I am opening the register user activity the app crashed and hence doesn't proceed further. Please help as I am quite new to android app development.

The logcat is here

2020-05-27 01:08:00.427 25788-25788/com.example.auth E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.auth, PID: 25788
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.auth/com.example.auth.RegisterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' 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.ProgressBar.setVisibility(int)' on a null object reference
        at com.example.auth.RegisterActivity.onCreate(RegisterActivity.java:35)
        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) 
2020-05-27 01:08:00.452 25788-25788/com.example.auth I/Process: Sending signal. PID: 25788 SIG: 9

Here is the RegisterActivity.java

package com.example.auth;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
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.database.FirebaseDatabase;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editTextName, editTextEmail, editTextPassword, editTextPhone;
    private ProgressBar progressBar;

    private FirebaseAuth mAuth;

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

        editTextName = findViewById(R.id.edit_text_name);
        editTextEmail = findViewById(R.id.edit_text_email);
        editTextPassword = findViewById(R.id.edit_text_password);
        editTextPhone = findViewById(R.id.edit_text_phone);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        **progressBar.setVisibility(View.GONE);**

        mAuth = FirebaseAuth.getInstance();

        findViewById(R.id.button_register).setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (mAuth.getCurrentUser() != null) {
            //handle the already login user
        }
    }

    private void registerUser() {
        final String name = editTextName.getText().toString().trim();
        final String email = editTextEmail.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();
        final String phone = editTextPhone.getText().toString().trim();

        if (name.isEmpty()) {
            editTextName.setError(getString(R.string.input_error_name));
            editTextName.requestFocus();
            return;
        }

        if (email.isEmpty()) {
            editTextEmail.setError(getString(R.string.input_error_email));
            editTextEmail.requestFocus();
            return;
        }

        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            editTextEmail.setError(getString(R.string.input_error_email_invalid));
            editTextEmail.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            editTextPassword.setError(getString(R.string.input_error_password));
            editTextPassword.requestFocus();
            return;
        }

        if (password.length() < 6) {
            editTextPassword.setError(getString(R.string.input_error_password_length));
            editTextPassword.requestFocus();
            return;
        }

        if (phone.isEmpty()) {
            editTextPhone.setError(getString(R.string.input_error_phone));
            editTextPhone.requestFocus();
            return;
        }

        if (phone.length() != 10) {
            editTextPhone.setError(getString(R.string.input_error_phone_invalid));
            editTextPhone.requestFocus();
            return;
        }


        progressBar.setVisibility(View.VISIBLE);
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if (task.isSuccessful()) {

                            User user = new User(
                                    name,
                                    email,
                                    phone
                            );

                            FirebaseDatabase.getInstance().getReference("Users")
                                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                    .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    progressBar.setVisibility(View.GONE);
                                    if (task.isSuccessful()) {
                                        Toast.makeText(RegisterActivity.this, getString(R.string.registration_success), Toast.LENGTH_LONG).show();
                                    } else {
                                        //display a failure message
                                    }
                                }
                            });

                        } else {
                            Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_register:
                registerUser();
                break;
        }
    }
}

Here is activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.example.auth.RegisterActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="vertical"
        android:padding="@dimen/default_padding">

        <TextView

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="cursive"
            android:text="@string/app_name"
            android:textAlignment="center"
            android:textColor="@color/colorText"
            android:textSize="@dimen/app_name_size" />

        <EditText
            android:id="@+id/edit_text_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_name"
            android:drawablePadding="@dimen/drawable_padding"
            android:hint="@string/full_name"
            android:nextFocusDown="@id/edit_text_email"
            android:textColor="@color/colorText"
            android:textColorHint="@color/colorHint" />


        <EditText
            android:id="@+id/edit_text_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_email"
            android:drawablePadding="@dimen/drawable_padding"
            android:hint="@string/email"
            android:inputType="textEmailAddress"
            android:nextFocusDown="@id/edit_text_password"
            android:textColor="@color/colorText"
            android:textColorHint="@color/colorHint" />


        <EditText
            android:id="@+id/edit_text_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_password"
            android:drawablePadding="@dimen/drawable_padding"
            android:hint="@string/password"
            android:inputType="textPassword"
            android:nextFocusDown="@id/edit_text_phone"
            android:textColor="@color/colorText"
            android:textColorHint="@color/colorHint" />

        <EditText
            android:id="@+id/edit_text_phone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:digits="0123456789"
            android:drawableLeft="@drawable/ic_phone"
            android:drawablePadding="@dimen/drawable_padding"
            android:hint="@string/phone"
            android:inputType="number"
            android:maxLength="10"
            android:nextFocusDown="@id/button_register"
            android:textColor="@color/colorText"
            android:textColorHint="@color/colorHint" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:checkedButton="@id/radioButton1"

            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/radioButton1"
                android:layout_width="118dp"
                android:layout_height="wrap_content"
                android:text="Student" />

            <RadioButton
                android:id="@+id/radioButton2"
                android:layout_width="135dp"
                android:layout_height="wrap_content"
                android:text="Institute" />

            <RadioButton
                android:id="@+id/radioButton3"
                android:layout_width="267dp"
                android:layout_height="wrap_content"
                android:text="Teacher" />
        </RadioGroup>

        <Button
            android:id="@+id/button_register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/bg_button_register"
            android:text="@string/register"
            android:textAllCaps="false"
            android:textColor="@color/colorText" />

    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

3 Answers3

0

The error message:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference

Is telling you that progressBar is null. You can't call methods on a null object. It's null because findViewById couldn't find a view with the given ID. You will have to examine your inflated. layout to figure out why that is.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • I have added the layout file the view is there with the given ID but still I am getting the error. Can you have a look please. – Raj Nayyar May 26 '20 at 20:01
0

Seems like you are setting the wrong layout in:

setContentView(R.layout.activity_main);

But you posted activity_register.xml

You should do something like:

setContentView(R.layout.activity_register);

If you try to invoke any method on any of your editTexts, you should get an NPE there as well.

Nullish Byte
  • 354
  • 2
  • 10
0

This is a typo:

setContentView(R.layout.activity_main);

but your layout is actually activity_register, not activity_main.

You probably meant:

setContentView(R.layout.activity_register);
Ryan M
  • 18,333
  • 31
  • 67
  • 74