-1

An error occurred java.lang.RuntimeException: Unable to start activity ComponentInfo.

Code Error:

 java.lang.RuntimeException: Unable to start activity 
 ComponentInfo{firebase.app.ph/firebase.app.ph.LoginActivity}: 
 java.lang.NullPointerException: Attempt to invoke virtual method 'void 
 android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2757)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2818)
 at android.app.ActivityThread.-wrap12(ActivityThread.java)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1557)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:163)
 at android.app.ActivityThread.main(ActivityThread.java:6393)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void 
 android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
 at firebase.app.ph.LoginActivity.onCreate(LoginActivity.java:57)
 at android.app.Activity.performCreate(Activity.java:6858)
 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2710)
 ... 9 more

Code app: StartActivity:

public class StartActivity extends AppCompatActivity {

Button login , register;

FirebaseUser firebaseUser;

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

    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

    if(firebaseUser!=null){
        startActivity(new Intent(StartActivity.this,MainActivity.class));
        finish();
    }
}

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


    login = findViewById(R.id.login);
    register = findViewById(R.id.register);

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

    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(StartActivity.this,RegisterActivity.class));
        }
    });
}
 }

LoginActivity:

public class LoginActivity extends AppCompatActivity {


EditText email, pass;
Button login;
TextView txtsignup;

FirebaseAuth auth;


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


    email = findViewById(R.id.email);
    login = findViewById(R.id.login);
    pass = findViewById(R.id.pass);
    txt_signup = findViewById(R.id.txtsignup);


    auth = FirebaseAuth.getInstance();

    txt_signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
        }
    });

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final ProgressDialog pd = new ProgressDialog(LoginActivity.this);
            pd.setMessage("Please wait...");
            pd.show();


            String str_email = email.getText().toString();
            String str_pass = pass.getText().toString();


            if (TextUtils.isEmpty(str_email) || TextUtils.isEmpty(str_pass)) {
                Toast.makeText(LoginActivity.this, "All Filed are required!", Toast.LENGTH_SHORT).show();
            } else {

                auth.signInWithEmailAndPassword(str_email, str_pass)
                        .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if (task.isSuccessful()) {
                                    DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Users").child(auth.getCurrentUser().getUid());

                                    reference.addValueEventListener(new ValueEventListener() {
                                        @Override
                                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                            pd.dismiss();
                                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                            startActivity(intent);
                                            finish();
                                        }

                                        @Override
                                        public void onCancelled(@NonNull DatabaseError databaseError) {
                                            pd.dismiss();
                                        }
                                    });
                                } else {
                                    pd.dismiss();
                                    Toast.makeText(LoginActivity.this, "!", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }
        }
    });

}

}

activity_login.xml

 <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout 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"
android:orientation="vertical"
android:gravity="center"
android:padding="10dp"
android:background="@drawable/b228"
tools:context=".LoginActivity">


<ImageView
    android:layout_width="wrap_content"
    android:layout_height="150dp"
    android:src="@drawable/image"></ImageView>




<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/edittext_background"
    android:hint="Email"
    android:layout_marginTop="15dp"
    android:id="@+id/email"
    android:inputType="textEmailAddress"
    android:padding="10dp"/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/edittext_background"
    android:hint="Password"
    android:layout_marginTop="15dp"
    android:id="@+id/pass"
    android:inputType="textPass"
    android:padding="10dp"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/login"
    android:text="Log in"
    android:textColor="@color/colorPrimary"
    android:background="@drawable/button_background"
    android:layout_marginTop="30dp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="!"
    android:id="@+id/txt_signup"
    android:textColor="@color/colorWhite"
    android:layout_marginTop="15dp"/>

I also have activity_register.xml and RegisterActivity, but they work great unlike Login. I just started programming in java and on Android Studio, so I will be glad to hear your answers!

JonnyKopow
  • 11
  • 3
  • Don't panic. You'll see more errors in the future. Have no idea about this one though. – Curiosa Globunznik Nov 24 '19 at 19:39
  • 1
    On the second glance, the stack trace says also " Caused by: java.lang.NullPointerException ... LoginActivity.onCreate(LoginActivity.java:57)". Does that make sense to you? – Curiosa Globunznik Nov 24 '19 at 19:41
  • I'm not familiar with this android stuff, just wanted to point out that actually there was a [NullPointerException](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) somewhere. The stack trace is truncated and there are further nested exceptions ("Caused by...") that maybe lead you to the culprit. – Curiosa Globunznik Nov 24 '19 at 20:00
  • Do you have more than one `activity_login.xml` in different folders? – laalto Nov 24 '19 at 20:33

1 Answers1

0

Reason of the error

This error is due to a bad practice you did in the naming conventions of the views in both of the activities. The code syntax is correct but the mistake is:

Look at activity_start.xml and activity_login.xml

The button in activity_start.xml and activity_login.xml has the same id as 'login'. Thus when you typed login = findViewById(R.id.login); in LoginActivity, it pointed to the view in the StartActivity which threw the NullPointerException


Solution

It's simple, just change the id of buttons in either of the layouts so that they are unique.

Community
  • 1
  • 1
  • Thank you, I'll try it now. Just in activity_register.xml I have a button with id that matches the id from activity_start.xml – JonnyKopow Nov 24 '19 at 20:21
  • But you didnt mention anything about activity_register.xml. You had only two layouts **activity_start.xml** and **activity_login.xml** and both had a button with same id as **login**. – Aman Nirala Nov 24 '19 at 20:26
  • Anyways just make sure to keep the **id** unique always. – Aman Nirala Nov 24 '19 at 20:27
  • ids don't need to be unique. It's perfectly fine to have the same id in two layouts like this. – laalto Nov 24 '19 at 20:31
  • @laalto Indeed its not mandatory to keep ids unique but its is always recommended and a good practice to keep them unique as they can generate conflicts sometimes later or sooner. – Aman Nirala Nov 24 '19 at 20:36
  • And I would like to add something more that if you are having same id in multiple layouts make sure to add references and refractions manually and avoid using the IDE's auto complete feature as it is usually the reason of these conflicts. – Aman Nirala Nov 24 '19 at 20:39
  • Most welcome @AlexDurak, did it solve the issue? – Aman Nirala Nov 24 '19 at 20:47
  • Yes, I followed your advice and made all id unique to avoid possible errors. – JonnyKopow Nov 24 '19 at 20:50
  • I am glad that I was of help. As you are new to the community, I would like to suggest you that if your problem is solved by an answer you can mark it as accepted as this will help people to find correct solution of the problem. So if this answer was helpful you can mark is as accepted. Thanks @AlexDurak – Aman Nirala Nov 24 '19 at 20:56