菜单项上的NullPointerException

时间:2019-06-26 10:51:08

标签: java android xml android-fragments

我正在尝试创建一个菜单,其中包含注销按钮。因此,我使用了Firebase-Auth。首先,我将btn_sign_out_itemButton更改为MenuItem,以将其放入菜单项列表中。但是,当我尝试启动应用程序时,会发生以下错误:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setEnabled(boolean)' on a null object reference

这是代码:

package com.nic.htv;

import android.app.SearchManager;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Toast;
import android.widget.Toolbar;


import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.IdpResponse;
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.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TextView mTextMessage;
    private DrawerLayout dl;
    private ActionBarDrawerToggle t;
    private NavigationView nv;
    FirebaseUser user;
    MenuItem btn_sign_out;


    // Write a message to the database
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("message");

    String value = "";
    Fragment fragment;

    private static final int MY_REQUEST_CODE = 9119; //AnyRandomNumber
    List<AuthUI.IdpConfig> providers;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        //mTextMessage = findViewById(R.id.message);



        ///////////////////
        //Navigation-Drawer
        dl = (DrawerLayout) findViewById(R.id.activity_main);
        t = new ActionBarDrawerToggle(this, dl, R.string.open, R.string.close);

        dl.addDrawerListener(t);
        t.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        nv = (NavigationView) findViewById(R.id.nv);
        nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();
                /*if (user.getEmail() != null){
                    MenuItem logout = (MenuItem) findViewById(R.id.btn_sign_out);
                    logout.setEnabled(true);
                }*/
                switch (id) {
                    case R.id.account:
                        Toast.makeText(MainActivity.this, "My Account", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.settings:
                        Toast.makeText(MainActivity.this, "Settings", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.mycart:
                        Toast.makeText(MainActivity.this, "My Cart", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.btn_sign_out_item:
                        Toast.makeText(MainActivity.this, "Logout", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        return true;
                }


                return true;

            }
        });

        //Navigation-Drawer Ende


        //ref = FirebaseDatabase.getInstance().getReference().child("User");

        //Login/Logout Firebase




        //INIT provider
        providers = Arrays.asList(
                new AuthUI.IdpConfig.EmailBuilder().build(), //EMAIL BUILDER
                new AuthUI.IdpConfig.GoogleBuilder().build()

        );

        showSignInOptions();


        // Read from the database
        myRef.addValueEventListener(new ValueEventListener() {

            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                //value = dataSnapshot.getValue(String.class);
                //mTextMessage.setText(value);
                Log.d("New Tag", "Value is: " + value);
            }


            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w("New Tag", "Failed to read value.", error.toException());
            }
        });

        BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
                = new BottomNavigationView.OnNavigationItemSelectedListener() {

            FragmentManager fm = getSupportFragmentManager();


            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.navigation_home:
                        //mTextMessage.setText(value);
                        fragment = new frag_01();
                        FragmentTransaction ft = fm.beginTransaction();
                        ft.replace(R.id.fragment_place, fragment);
                        ft.commit();
                        return true;
                    case R.id.navigation_dashboard:
                        //Intent myIntent = new Intent(MainActivity.this, dashboard_activity.class);
                        //startActivity(myIntent);
                        fragment = new list_frag();
                        FragmentTransaction ft2 = fm.beginTransaction();
                        ft2.replace(R.id.fragment_place, fragment);
                        ft2.commit();
                        return true;
                    case R.id.navigation_notifications:
                        fragment = new frag_03();
                        FragmentTransaction ft3 = fm.beginTransaction();
                        ft3.replace(R.id.fragment_place, fragment);
                        ft3.commit();
                        return true;
                    case R.id.iconhamburger:
                        fragment = new frag_02();
                        FragmentTransaction ft4 = fm.beginTransaction();
                        ft4.replace(R.id.fragment_place, fragment);
                        ft4.commit();
                        return true;
                }
                return true;
            }
        };

        navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);


    }

    private void showSignInOptions() {
        startActivityForResult(
                AuthUI.getInstance().createSignInIntentBuilder()
                        .setAvailableProviders(providers)
                        .setTheme(R.style.LoginLogout)
                        .build(), MY_REQUEST_CODE
        );
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        btn_sign_out = (MenuItem) findViewById(R.id.btn_sign_out_item);
        if (requestCode == MY_REQUEST_CODE) {
            IdpResponse response = IdpResponse.fromResultIntent(data);
            if (resultCode == RESULT_OK) {
                //GetUser
                user = FirebaseAuth.getInstance().getCurrentUser();
                //Show email on toast
                Toast.makeText(this, "" + user.getEmail(), Toast.LENGTH_SHORT).show();
                btn_sign_out.setEnabled(true);
            } else {
                Toast.makeText(this, "" + response.getError().getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

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

        //WRITE
        //myRef.setValue("EBIN!");


        //READ

    }


    //Navigation-Drawer-Script
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (t.onOptionsItemSelected(item))
            return true;
        switch (item.getItemId()) {

            case R.id.btn_sign_out_item:
                AuthUI.getInstance()
                        .signOut(MainActivity.this)
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                btn_sign_out.setEnabled(false);
                                showSignInOptions();
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            default:
                return super.onOptionsItemSelected(item);

        }
        }
        //Navigation-DrawerScript-Ende


}`

这是xml navigation_menu.xml

    <?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/account"
        android:icon="@drawable/online"
        android:title="My Account"/>

    <item android:id="@+id/settings"
        android:icon="@drawable/online"
        android:title="Settings"/>

    <item android:id="@+id/mycart"
        android:icon="@drawable/online"
        android:title="My Cart"/>
    <item
        android:title="Logout"
        android:id="@+id/btn_sign_out_item"
        android:visibility="visible"
        android:enabled="false" />

</menu>

这是main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <TextView
        android:id="@+id/message"
        android:layout_width="381dp"
        android:layout_height="528dp"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:text="@string/title_home"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />



    <fragment
        android:id="@+id/fragment_place"
        android:name="com.nic.htv.frag_01"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="16dp"
        tools:layout="@layout/fragment_frag_01"></fragment>

    </android.support.constraint.ConstraintLayout>
    <android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:menu="@menu/navigation_menu"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_header"
        android:id="@+id/nv">

    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

1 个答案:

答案 0 :(得分:2)

首先,您必须将其缩写:

片段中:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.yourMenuName, menu);
}

活动中:

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourMenuName, menu);
    return true;

}

然后您就可以使用它了。


更新:

在初始化菜单以供菜单中的每个项目使用之后,您也必须将其初始化,如下所示:

Menu menu = navigationView.getMenu();
menu.findItem(R.id.account).setEnabled(true); 

我初始化您的account ID,您可以对菜单中的settingsmycartbtn_sign_out_item ide进行类似的操作。