首页 > 解决方案 > 我的应用程序在显示启动画面后无法启动另一个活动,并且显示此错误

问题描述

Activity我的应用程序在显示启动画面后无法启动另一个。这是我在运行我的应用程序时遇到的错误:

例外:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ref, PID: 7683
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ref/com.example.ref.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        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:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
        at com.example.ref.LoginActivity.onCreate(LoginActivity.java:46)
        at android.app.Activity.performCreate(Activity.java:8000)
        at android.app.Activity.performCreate(Activity.java:7984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
        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:2066) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:223) 
        at android.app.ActivityThread.main(ActivityThread.java:7656) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 7683 SIG: 9
Disconnected from the target VM, address: 'localhost:49932', transport: 'socket'

SpalshScreen:

    package com.example.ref;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    import android.content.Intent;
    import android.os.Handler;
    
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.FirebaseUser;

    public class SpalshScreen extends AppCompatActivity {
        FirebaseUser currentUser;
        private FirebaseAuth mAuth;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_spalsh_screen2);
            mAuth = FirebaseAuth.getInstance();
            if (mAuth != null) {
                currentUser = mAuth.getCurrentUser(); }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    FirebaseUser user = mAuth.getCurrentUser();
                    if (user == null) {
                        Intent intent = new Intent(SpalshScreen.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Intent mainIntent = new Intent(SpalshScreen.this, DashboardActivity.class);
                        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(mainIntent);
                        finish();
                    }
                }
            }, 1000);
        }
    }

LoginActivity:

    package com.example.ref;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.text.InputType;
    import android.util.Patterns;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import androidx.annotation.NonNull;
    import androidx.appcompat.app.ActionBar;
    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.OnFailureListener;
    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;
    import com.google.firebase.database.DatabaseReference;
    import com.google.firebase.database.FirebaseDatabase;
    
    import java.util.HashMap;
    import java.util.Objects;
    
    public class LoginActivity extends AppCompatActivity {
    
        private EditText email, password, name;
        private Button mlogin;
        private TextView newdnewaccount, reocverpass;
        FirebaseUser currentUser;
        private ProgressDialog loadingBar;
        private FirebaseAuth mAuth;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            ActionBar actionBar = getSupportActionBar();
            actionBar.setTitle("Create Account");
            actionBar.setDisplayShowHomeEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
    
            // initialising the layout items
            email = findViewById(R.id.login_email);
            password = findViewById(R.id.login_password);
            newdnewaccount = findViewById(R.id.needs_new_account);
            reocverpass = findViewById(R.id.forgetp);
            mAuth = FirebaseAuth.getInstance();
            mlogin = findViewById(R.id.login_button);
            loadingBar = new ProgressDialog(this);
            mAuth = FirebaseAuth.getInstance();
    
            // checking if user is null or not
            if (mAuth != null) {
                currentUser = mAuth.getCurrentUser();
            }
    
            mlogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String emaill = email.getText().toString().trim();
                    String pass = password.getText().toString().trim();
    
                    // if format of email doesn't matches return null
                    if (!Patterns.EMAIL_ADDRESS.matcher(emaill).matches()) {
                        email.setError("Invalid Email");
                        email.setFocusable(true);
    
                    } else {
                        loginUser(emaill, pass);
                    }
                }
            });
    
            // If new account then move to Registration Activity
            newdnewaccount.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(LoginActivity.this, RegistrationActivity.class));
                }
            });
    
            // Recover Your Password using email
            reocverpass.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showRecoverPasswordDialog();
                }
            });
        }
    
        private void showRecoverPasswordDialog() {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Recover Password");
            LinearLayout linearLayout = new LinearLayout(this);
            final EditText emailet = new EditText(this);//write your registered email
            emailet.setText("Email");
            emailet.setMinEms(16);
            emailet.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
            linearLayout.addView(emailet);
            linearLayout.setPadding(10, 10, 10, 10);
            builder.setView(linearLayout);
            builder.setPositiveButton("Recover", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String emaill = emailet.getText().toString().trim();
                    beginRecovery(emaill);//send a mail on the mail to recover password
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
    
        private void beginRecovery(String emaill) {
            loadingBar.setMessage("Sending Email....");
            loadingBar.setCanceledOnTouchOutside(false);
            loadingBar.show();
    
            // send reset password email
            mAuth.sendPasswordResetEmail(emaill).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    loadingBar.dismiss();
                    if (task.isSuccessful()) {
                        Toast.makeText(LoginActivity.this, "Done sent", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(LoginActivity.this, "Error Occured", Toast.LENGTH_LONG).show();
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    loadingBar.dismiss();
                    Toast.makeText(LoginActivity.this, "Error Failed", Toast.LENGTH_LONG).show();
                }
            });
        }
    
        private void loginUser(String emaill, String pass) {
            loadingBar.setMessage("Logging In....");
            loadingBar.show();
    
            // sign in with email and password after authenticating
            mAuth.signInWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
    
                    if (task.isSuccessful()) {
    
                        loadingBar.dismiss();
                        FirebaseUser user = mAuth.getCurrentUser();
    
                        if (task.getResult().getAdditionalUserInfo().isNewUser()) {
                            String email = user.getEmail();
                            String uid = user.getUid();
                            HashMap<Object, String> hashMap = new HashMap<>();
                            hashMap.put("email", email);
                            hashMap.put("uid", uid);
                            hashMap.put("name", "");
                            hashMap.put("onlineStatus", "online");
                            hashMap.put("typingTo", "noOne");
                            hashMap.put("phone", "");
                            hashMap.put("image", "");
                            hashMap.put("cover", "");
                            FirebaseDatabase database = FirebaseDatabase.getInstance();
    
                            // store the value in Database in "Users" Node
                            DatabaseReference reference = database.getReference("Users");
    
                            // storing the value in Firebase
                            reference.child(uid).setValue(hashMap);
                        }
                        Toast.makeText(LoginActivity.this, "Registered User " + user.getEmail(), Toast.LENGTH_LONG).show();
                        Intent mainIntent = new Intent(LoginActivity.this, DashboardActivity.class);
                        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(mainIntent);
                        finish();
                    } else {
                        loadingBar.dismiss();
                        Toast.makeText(LoginActivity.this, "Login Failed", Toast.LENGTH_LONG).show();
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    loadingBar.dismiss();
                    Toast.makeText(LoginActivity.this, "Error Occured", Toast.LENGTH_LONG).show();
                }
            });
        }
    
        @Override
        public boolean onSupportNavigateUp() {
            onBackPressed();
            return super.onSupportNavigateUp();
        }
    }







 
        <resources xmlns:tools="http://schemas.android.com/tools">
            <!-- Base application theme. -->
            <style name="Theme.Ref" parent="Theme.MaterialComponents.DayNight.NoActionBar">
                <!-- Primary brand color. -->
                <item name="colorPrimary">@color/purple_500</item>
                <item name="colorPrimaryVariant">@color/purple_700</item>
                <item name="colorOnPrimary">@color/white</item>
                <!-- Secondary brand color. -->
                <item name="colorSecondary">@color/teal_200</item>
                <item name="colorSecondaryVariant">@color/teal_700</item>
                <item name="colorOnSecondary">@color/black</item>
                <!-- Status bar color. -->
                <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
                <!-- Customize your theme here. -->
            </style>
        </resources>




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/welcom"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="120dp"
                android:layout_marginTop="50dp"
                android:text="Welcome!"
                android:textColor="@color/colorBlack"
                android:textSize="30sp"
                android:textStyle="italic|bold" />

            <TextView
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/welcom"
                android:layout_marginStart="35dp"
                android:layout_marginTop="120dp"
                android:text="Email"
                android:textColor="@color/colorBlack" />

            <EditText
                android:id="@+id/login_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/email"
                android:layout_alignParentStart="true"
                android:layout_marginLeft="30dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="30dp"
                android:background="@drawable/edit"
                android:drawableStart="@drawable/ic_email"
                android:hint="Email..."
                android:inputType="textEmailAddress"
                android:padding="8dp" />

            <TextView
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/login_email"
                android:layout_marginStart="32dp"
                android:layout_marginTop="20dp"
                android:text="Password"
                android:textColor="@color/colorBlack" />

            <EditText
                android:id="@+id/login_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/password"
                android:layout_alignParentStart="true"
                android:layout_marginLeft="30dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="30dp"
                android:background="@drawable/edit"
                android:drawableStart="@drawable/password"
                android:hint="Password..."
                android:inputType="textPassword"
                android:padding="8dp" />

            <TextView
                android:id="@+id/forgetp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/login_password"
                android:layout_marginStart="210dp"
                android:layout_marginTop="15dp"
                android:layout_marginEnd="23dp"
                android:text="@string/forget_password"
                android:textAlignment="center"
                android:textColor="@color/colorPrimaryDark"
                android:textSize="17sp"
                android:textStyle="bold" />

            <Button
                android:id="@+id/login_button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/forgetp"
                android:layout_marginLeft="30dp"
                android:layout_marginTop="15dp"
                android:layout_marginRight="30dp"
                android:background="@drawable/buttonss"
                android:padding="4dp"
                android:text="Login"
                android:textAllCaps="false"
                android:textColor="@android:color/background_light"
                android:textSize="24sp" />

            <TextView
                android:id="@+id/needs_new_account"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/login_button"
                android:layout_centerHorizontal="true"
                android:layout_marginStart="15dp"
                android:layout_marginTop="20dp"
                android:layout_marginEnd="23dp"
                android:text="@string/need_new_account_sign_up_here"
                android:textAlignment="center"
                android:textColor="@color/colorPrimary"
                android:textSize="17sp"
                android:textStyle="bold" />
        </RelativeLayout>

    </ScrollView>

</LinearLayout>

标签: android-studio

解决方案


当编译器onCreate()在您的第二个活动中启动时,他找不到对您尝试的对象的引用setTitle(),因此基本上您的ToolbarActionBar没有对 View(xml) 中的对象的引用。

前任:

Toolbar toolbar = findViewById(R.id.name_of_the_object);

以这种方式toolbar获取对视图中对象的引用(activity.xml);


推荐阅读