0

I am getting stuck at this error. I am not getting where it goes wrong so I have gone through Logcat and there I saw this Fatal Exception. How to fix this error? I know here on the forum are a lot of pages describing solution for my problem.

I had read many forums fixing this exception but I didn't got the solution which will fixied this error.

E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.example.easylearn, PID: 11793
 java.lang.RuntimeException: Unable to instantiate activity 
 ComponentInfo{com.example.easylearn/com.example.easylearn.MainActivity}: 
 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context 
 android.content.Context.getApplicationContext()' on a null object reference
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
 at android.app.ActivityThread.-wrap11(ActivityThread.java)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:148)
 at android.app.ActivityThread.main(ActivityThread.java:5417)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 
 'android.content.Context android.content.Context.getApplicationContext()' on a null object 
 reference
 at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
 at com.example.easylearn.MainActivity.<init>(MainActivity.java:21)
 at java.lang.Class.newInstance(Native Method)
 at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
 at android.app.ActivityThread.-wrap11(ActivityThread.java) 
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
 at android.os.Handler.dispatchMessage(Handler.java:102) 
 at android.os.Looper.loop(Looper.java:148) 
 at android.app.ActivityThread.main(ActivityThread.java:5417)
 at java.lang.reflect.Method.invoke(Native Method) 
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616

This is my AndroidManifest.xml.

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.easylearn">

 <application
  android:allowBackup="true"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:supportsRtl="true"
  android:theme="@style/AppTheme">
  <activity android:name=".HomeActivity"></activity>
  <activity android:name=".LoginActivity" />
  <activity android:name=".MainActivity">
  <intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
  </activity>
  </application>
  </manifest>

This is my MainActivity.java

  package com.example.easylearn;
  import androidx.annotation.NonNull;
  import androidx.appcompat.app.AppCompatActivity;
  import android.content.Intent;
  import android.media.MediaPlayer;
  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.FirebaseAuth;
  public class MainActivity extends AppCompatActivity {
  AppCompatActivity appCompatActivity = new LoginActivity(getApplicationContext());
  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 id");
  emailId.requestFocus();
  }
  else if(pwd.isEmpty())
  {
  password.setError("Please enter password");
  password.requestFocus();
  }
  else if(email.isEmpty() && pwd.isEmpty())
  {
  Toast.makeText(MainActivity.this,"Fiels are Empty!",Toast.LENGTH_SHORT).show();
  }
  else if(!(email.isEmpty() && pwd.isEmpty()))
  {
  mFirebaseAuth.createUserWithEmailAndPassword(email,pwd).addOnCompleteListener(MainActivity.this,
  new OnCompleteListener<com.google.firebase.auth.AuthResult>() {
  @Override
  public void onComplete(@NonNull Task<com.google.firebase.auth.AuthResult> task) 
  {
  if(task.isSuccessful())
  {
  Toast.makeText(MainActivity.this,"SignUp Unsuccessful,Please Try 
  Again..",Toast.LENGTH_SHORT).show();
  }
  else {
  startActivity(new Intent(MainActivity.this,HomeActivity.class));
  }
  }
  });
  }
  else
  {
  Toast.makeText(MainActivity.this,"Error Occured!",Toast.LENGTH_SHORT).show();
  }
  }
  });
  tvSignIn.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  Intent i = new Intent(MainActivity.this,LoginActivity.class);
  startActivity(i);
  }
  });
  }
  }

This is my LoginActivity.java

  package com.example.easylearn;

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

  import android.content.Context;
  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.firebase.auth.FirebaseUser;
  import com.google.android.gms.tasks.OnCompleteListener;
  import com.google.android.gms.tasks.Task;
  import com.google.firebase.auth.FirebaseAuth;

  public class LoginActivity extends AppCompatActivity {

  private Context ctx;
  public LoginActivity(Context ctx){
  this.ctx = ctx;
  }

  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 id");
  emailId.requestFocus();
  }
  else if(pwd.isEmpty())
  {
  password.setError("Please enter password");
  password.requestFocus();
  }
  else if(email.isEmpty() && pwd.isEmpty())
  {
  Toast.makeText(LoginActivity.this,"Fiels are Empty!",Toast.LENGTH_SHORT).show();
  }
  else if(!(email.isEmpty() && pwd.isEmpty()))
  {

  mFirebaseAuth.signInWithEmailAndPassword(email,pwd).addOnCompleteListener(LoginActivity.this, new 
  OnCompleteListener<com.google.firebase.auth.AuthResult>() {
  @Override
  public void onComplete(@NonNull Task<com.google.firebase.auth.AuthResult> task) 
  {
  if(!task.isSuccessful()){
  Toast.makeText(ctx,"Login Error,Please Login      
  again..",Toast.LENGTH_SHORT).show();
  }
  else{
  Intent inToHome = new Intent(LoginActivity.this,HomeActivity.class);
  startActivity(inToHome);
  }
  }
  });
  }
  else
  {
  Toast.makeText(ctx,"Error Occured!",Toast.LENGTH_SHORT).show();
  }
  }
  });

  tvSignUp.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  Intent intSignUp = new Intent(LoginActivity.this,MainActivity.class);
  startActivity(intSignUp);
  }
  });
  }

  @Override
  protected void onStart() {
  super.onStart();
  mFirebaseAuth.addAuthStateListener(mAuthStateListener);
  }
  }`
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Possible duplicate of [java.lang.RuntimeException: Unable to instantiate activity ComponentInfo](https://stackoverflow.com/questions/4688277/java-lang-runtimeexception-unable-to-instantiate-activity-componentinfo) – grrigore Oct 26 '19 at 12:48

1 Answers1

0

The stacktrace says you're calling getApplicationContext() too early, in MainActivity init phase.

It seems to come from this:

AppCompatActivity appCompatActivity = new LoginActivity(getApplicationContext());

Remove this line altogether. You're not using the field for anything and new is not the mechanism for creating new activity objects --- let the Android framework do that for you with startActivity().

While there, you need to remove these in LoginActivity, too:

private Context ctx;
public LoginActivity(Context ctx){
this.ctx = ctx;
}

Activities need a no-arg constructor so the framework can instantiate them for you. An Activity is-a Context so passing a Context around is not needed anyway.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • then if i converted this line (Toast.makeText(ctx,"Login Error,Please Login again..",Toast.LENGTH_SHORT).show();) to (Toast.makeText(MainActivity.this,"Login Error,Please Login again..",Toast.LENGTH_SHORT).show();) They are giving me error MainActivity is not an enclosing class – Kaveri Mandlik Oct 26 '19 at 13:09
  • You need `LoginActivity.this` to refer to the `LoginActivity` instance – laalto Oct 26 '19 at 13:10
  • I run it successfully, made changes as per you recommended but after sign up, it should show the user in firebase user section but they are not showing user information – Kaveri Mandlik Oct 26 '19 at 13:45
  • Please help me out – Kaveri Mandlik Oct 26 '19 at 13:59