Activity 第二次通过 Intent 启动时崩溃

Activity crashing the second time it is launched through intent

我正在使用 firebase 设计一个简单的 store/retrieve 数据 android 应用程序。

Activity1是登录activity,用户登录成功后直接进入Activity2。第一次登录没有问题,一切都在里面合适的地方。我在 Activity2 中有一个导航抽屉,我用它来切换片段,在那个导航抽屉中,用户可以注销并返回登录 activity。以下是 Activity2 的摘录,它将用户带回登录 activity

            case R.id.nav_logout:
            account_key = "";
            Toast.makeText(getApplicationContext(), "Logged Out", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(intent);
            finish();
            break;

当我单击注销按钮时,我会按原样转到 Activity1。现在的问题是当我尝试再次登录时,应用程序崩溃并出现以下错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.adzu.bfarsystem, PID: 2143
    java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.add(int, int, int, java.lang.CharSequence)' on a null object reference
        at android.view.MenuInflater$MenuState.addItem(MenuInflater.java:540)
        at android.view.MenuInflater.parseMenu(MenuInflater.java:193)
        at android.view.MenuInflater.inflate(MenuInflater.java:114)
        at androidx.appcompat.view.SupportMenuInflater.inflate(SupportMenuInflater.java:120)
        at com.adzu.bfarmobile.activities.MainActivity.createSearchView(MainActivity.java:153)
        at com.adzu.bfarmobile.activities.MainActivity.dataRetrieved(MainActivity.java:109)
        at com.adzu.bfarmobile.entities.DatabaseReader.onChildAdded(DatabaseReader.java:64)
        at com.google.firebase.database.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:79)
        at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
        at com.google.firebase.database.core.view.EventRaiser.run(EventRaiser.java:55)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        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)

下面是触发错误的行:

LoginActivity.java 第 95-102 行

               if (activated) {
                    Toast.makeText(getApplicationContext(), "Login Success!", Toast.LENGTH_LONG).show();

                    Intent newIntent = new Intent(getApplicationContext(), MainActivity.class);
                    newIntent.putExtra("account_key", dataSnapshot.getKey());
                    startActivity(newIntent);
                    finish();
                }

MainActivity.java 95-127 行

Intent intent = getIntent();
account_key = intent.getStringExtra("account_key");

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("account");
DatabaseReader.readDataByKey(account_key, ref, new OnGetDataListener() {
    @Override
    public void dataRetrieved(DataSnapshot dataSnapshot) {
        Account user = new Account((Map<String, Object>) dataSnapshot.getValue());
        fragment1 = new ListFragment();
        fragment1.setUser(user);
        createSearchView();
        showSearchView();
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment1).commit();
        navigationView.setCheckedItem(R.id.nav_operatorlist);
        TextView acct_name = findViewById(R.id.acct_name);
        acct_name.setText("Logged in as: " + user.getUsername());
    }

    @Override
    public void dataExists(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onStart() {

    }

    @Override
    public void onFailure() {

    }
});

MainActivity.java 第 141-153 行

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
    return super.onCreateOptionsMenu(menu);
}

public void createSearchView(){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_menu, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    searchView = findViewById(R.id.search_view);
    searchView.setMenuItem(searchItem);
    expandableLayout = findViewById(R.id.expandable_layout);

DatabaseReader.java 第 64-89 行

    public static void readDataByKey(String account_key, DatabaseReference ref, final OnGetDataListener listener) {
        listener.onStart();
        Query query = ref.orderByKey().equalTo(account_key);
        query.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                listener.dataRetrieved(dataSnapshot);
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                listener.onFailure();
            }
        });

    }

如有任何帮助,我们将不胜感激。谢谢!

您可能 运行 进入竞争状态。 您可能在系统调用 onCreateOptionsMenu 之前调用了 createSearchView,因此菜单为 null.

尝试让 onCreateOptionsMenu 在行后调用 createSearchView

this.menu = menu;