This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


4年前关闭。




我正在尝试实现DropDownMenu https://github.com/JayFang1993/DropDownMenu

我有此代码的问题:

主要活动

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import com.jayfang.dropdownmenu.DropDownMenu;
import com.jayfang.dropdownmenu.OnMenuSelectedListener;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu;
import com.oguzdev.circularfloatingactionmenu.library.SubActionButton;
import com.sai.eventee.rss.ServiceStarter;
import com.sai.eventee.util.ScrimInsetsFrameLayout;
import com.sai.eventee.web.WebviewFragment;

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

public class MainActivity extends AppCompatActivity implements
        NavDrawerCallback {

    private Toolbar mToolbar;
    private NavDrawerFragment mNavigationDrawerFragment;

    public static String DATA = "transaction_data";
    public static String EMBEDD_DATA = "embedd";

    SharedPreferences prefs;
    boolean openedByBackPress = false;
    //=======================================================
    private DropDownMenu mMenu;
    private ListView mList;

    private int city_index;
    private int sex_index;
    private int age_index;
    private List<String> data;
    final String[] arr1=new String[]{"全部城市","北京","上海","广州","深圳"};
    final String[] arr2=new String[]{"性别","男","女"};
    final String[] arr3=new String[]{"全部年龄","10","20","30","40","50","60","70"};

    final String[] strings=new String[]{"选择城市","选择性别","选择年龄"};

    private FloatingActionButton mFAB;
    private FloatingActionMenu mFABMenu;
    //=======================================================

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupFAB();


        boolean newDrawer = getResources().getBoolean(R.bool.newdrawer);

        if (newDrawer == true) {
            setContentView(R.layout.activity_main_alternate);
        } else {
            setContentView(R.layout.activity_main);
            Helper.setStatusBarColor(MainActivity.this, getResources()
                    .getColor(R.color.myPrimaryDarkColor));
        }

        mMenu=(DropDownMenu)findViewById(R.id.menu);

        mMenu.setmMenuCount(3);
        mMenu.setmShowCount(6);
        mMenu.setShowCheck(true);
        mMenu.setmMenuTitleTextSize(16);
        mMenu.setmMenuTitleTextColor(Color.parseColor("#777777"));
        mMenu.setmMenuListTextSize(16);
        mMenu.setmMenuListTextColor(Color.BLACK);
        mMenu.setmMenuBackColor(Color.parseColor("#eeeeee"));
        mMenu.setmMenuPressedBackColor(Color.WHITE);
        mMenu.setmMenuPressedTitleTextColor(Color.BLACK);

        mMenu.setmCheckIcon(R.drawable.ico_make);

        mMenu.setmUpArrow(R.drawable.arrow_up);
        mMenu.setmDownArrow(R.drawable.arrow_down);

        mMenu.setDefaultMenuTitle(strings);


        mMenu.setShowDivider(false);
        mMenu.setmMenuListBackColor(getResources().getColor(R.color.white));
        mMenu.setmMenuListSelectorRes(R.color.white);
        mMenu.setmArrowMarginTitle(20);

        mMenu.setMenuSelectedListener(new OnMenuSelectedListener() {
            @Override
            public void onSelected(View listview, int RowIndex, int ColumnIndex) {
                Log.i("MainActivity", "select " + ColumnIndex + " column and " + RowIndex + " row");
                if (ColumnIndex == 0) {
                    city_index = RowIndex;
                } else if (ColumnIndex == 1) {
                    sex_index = RowIndex;
                } else {
                    age_index = RowIndex;
                }
                //过滤筛选
                setFilter();
            }
        });
        List<String[]> items = new ArrayList<>();
        items.add(arr1);
        items.add(arr2);
        items.add(arr3);
        mMenu.setmMenuItems(items);


        mMenu.setIsDebug(false);

        mList=(ListView)findViewById(R.id.lv_list);
        data=getData();
        mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, data));

        mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        mNavigationDrawerFragment = (NavDrawerFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_drawer);

        if (newDrawer == true) {
            mNavigationDrawerFragment.setup(R.id.scrimInsetsFrameLayout,
                    (DrawerLayout) findViewById(R.id.drawer), mToolbar);
            mNavigationDrawerFragment
                    .getDrawerLayout()
                    .setStatusBarBackgroundColor(
                            getResources().getColor(R.color.myPrimaryDarkColor));

            ((ScrimInsetsFrameLayout) findViewById(R.id.scrimInsetsFrameLayout)).getLayoutParams().width = getDrawerWidth();
        } else {
            mNavigationDrawerFragment.setup(R.id.fragment_drawer,
                    (DrawerLayout) findViewById(R.id.drawer), mToolbar);

            DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mNavigationDrawerFragment.getView().getLayoutParams();
            params.width = getDrawerWidth();
            mNavigationDrawerFragment.getView().setLayoutParams(params);
        }

        prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

        // setting push enabled
        String push = getString(R.string.rss_push_url);
        if (null != push && !push.equals("")) {
            // Create object of SharedPreferences.
            boolean firstStart = prefs.getBoolean("firstStart", true);

            if (firstStart) {

                final ServiceStarter alarm = new ServiceStarter();

                SharedPreferences.Editor editor = prefs.edit();

                alarm.setAlarm(this);
                // now, just to be sure, where going to set a value to check if
                // notifications is really enabled
                editor.putBoolean("firstStart", false);
                // commits your edits
                editor.commit();
            }

        }

        // Checking if the user would prefer to show the menu on start
        boolean checkBox = prefs.getBoolean("menuOpenOnStart", false);
        if (checkBox == true) {
            mNavigationDrawerFragment.openDrawer();
        }

        // New imageloader
        Helper.initializeImageLoader(this);


    }


    private void setFilter(){
        List<String> temp=new ArrayList<String>();
        for (int i=0;i<getData().size();i++){
            boolean city=((city_index==0)?true:data.get(i).contains(arr1[city_index]));
            boolean sex=((sex_index==0)?true:data.get(i).contains(arr2[sex_index]));
            boolean age=((age_index==0)?true:data.get(i).contains(arr3[age_index]));
            if(city && sex && age){
                temp.add(data.get(i));
            }
        }
        mList.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_expandable_list_item_1,temp));
    }

    private List<String> getData(){
        List<String> data = new ArrayList<String>();
        data.add("上海-男-10");
        data.add("上海-男-20");
        data.add("上海-男-30");
        data.add("上海-男-40");
        data.add("上海-男-50");
        data.add("上海-男-60");
        data.add("上海-男-70");
        data.add("广州-男-10");
        data.add("广州-女-10");
        data.add("北京-男-20");
        data.add("北京-女-10");
        data.add("广州-男-10");
        data.add("北京-男-10");
        data.add("广州-男-10");
        data.add("上海-女-60");
        data.add("上海-女-20");
        return data;
    }


        private void setupFAB() {
        //define the icon for the main floating action button
        ImageView iconFAB = new ImageView(this);
        iconFAB.setImageResource(R.drawable.ic_action_new);

        //set the appropriate background for the main floating action button along with its icon
        mFAB = new FloatingActionButton.Builder(this)
                .setContentView(iconFAB)
                .setBackgroundDrawable(R.drawable.selector_button_red)
                .build();

        //define the icons for the sub action buttons
        ImageView iconSortName = new ImageView(this);
        iconSortName.setImageResource(R.drawable.ic_action_alphabets);
        ImageView iconSortDate = new ImageView(this);
        iconSortDate.setImageResource(R.drawable.ic_action_calendar);
        ImageView iconSortRatings = new ImageView(this);
        iconSortRatings.setImageResource(R.drawable.ic_action_important);

        //set the background for all the sub buttons
        SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
        itemBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_sub_button_gray));


        //build the sub buttons
        SubActionButton buttonSortName = itemBuilder.setContentView(iconSortName).build();
        SubActionButton buttonSortDate = itemBuilder.setContentView(iconSortDate).build();
        SubActionButton buttonSortRatings = itemBuilder.setContentView(iconSortRatings).build();

            /*
        //to determine which button was clicked, set Tags on each button
        buttonSortName.setTag(TAG_SORT_NAME);
        buttonSortDate.setTag(TAG_SORT_DATE);
        buttonSortRatings.setTag(TAG_SORT_RATINGS);

        buttonSortName.setOnClickListener(this);
        buttonSortDate.setOnClickListener(this);
        buttonSortRatings.setOnClickListener(this);
        */
        //add the sub buttons to the main floating action button
        mFABMenu = new FloatingActionMenu.Builder(this)
                .addSubActionView(buttonSortName)
                .addSubActionView(buttonSortDate)
                .addSubActionView(buttonSortRatings)
                .attachTo(mFAB)
                .build();
    }
    //===============================================================================*/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // getMenuInflater().inflate(R.menu.rss_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onNavigationDrawerItemSelected(int position, NavItem item) {
        Fragment fragment;
        try {
            fragment = item.getFragment().newInstance();
            if (fragment != null) {

                Bundle bundle = new Bundle();
                String extra;

                String license = getResources().getString(R.string.google_play_license);

                // if item does not require purchase, or app has purchased, or license is null/empty (app has no in app purchases)
                if (item.requiresPurchase() == true
                        && !SettingsFragment.getIsPurchased(this)
                        && null != license && !license.equals("")) {
                    fragment = new SettingsFragment();
                    extra = SettingsFragment.SHOW_DIALOG;
                } else {
                    extra = item.getData();
                }

                bundle.putString(DATA, extra);
                fragment.setArguments(bundle);

                FragmentManager fragmentManager = getSupportFragmentManager();

                fragmentManager.beginTransaction()
                        .replace(R.id.container, fragment).commit();

                setTitle(item.getText());

                if (null != MainActivity.this.getSupportActionBar()
                        && null != MainActivity.this.getSupportActionBar()
                                .getCustomView()) {
                    MainActivity.this.getSupportActionBar().setDisplayOptions(
                            ActionBar.DISPLAY_SHOW_HOME
                                    | ActionBar.DISPLAY_SHOW_TITLE);
                }

            } else {
                // error in creating fragment
                Log.e("MainActivity", "Error in creating fragment");
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        Fragment webview = getSupportFragmentManager().findFragmentById(
                R.id.container);

        if (mNavigationDrawerFragment.isDrawerOpen()) {
            mNavigationDrawerFragment.closeDrawer();
        } else if (webview instanceof WebviewFragment) {
            boolean goback = ((WebviewFragment) webview).canGoBack();
            if (!goback)
                super.onBackPressed();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null) {
            for (Fragment frag : fragments)
                frag.onActivityResult(requestCode, resultCode, data);
        }
    }

    private int getDrawerWidth(){
        // Navigation Drawer layout width
        int width = getResources().getDisplayMetrics().widthPixels;

        TypedValue tv = new TypedValue();
        int actionBarHeight;
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
        {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
        } else {
            actionBarHeight = 0;
        }

        int possibleMinDrawerWidth = width - actionBarHeight;

        int maxDrawerWidth = getResources().getDimensionPixelSize(R.dimen.drawer_width);

        return Math.min(possibleMinDrawerWidth, maxDrawerWidth);
    }
}


Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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">


    <include
        android:id="@+id/toolbar_actionbar"
        layout="@layout/toolbar_default"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar_actionbar">


        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
        <com.jayfang.dropdownmenu.DropDownMenu
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:id="@+id/menu"
            android:background="@color/ripple_material_dark"
            android:layout_height="60dp"/>

        <ListView
            android:layout_width="fill_parent"
            android:layout_below="@id/menu"
            android:id="@+id/lv_list"
            android:background="#ffffff"
            android:layout_height="wrap_content"></ListView>
        <!-- android:layout_marginTop="?android:attr/actionBarSize"-->
        <fragment
            android:id="@+id/fragment_drawer"
            android:name="com.sai.eventee.NavDrawerFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:layout="@layout/drawer_fragment"
            tools:layout="@layout/drawer_fragment" />
    </android.support.v4.widget.DrawerLayout>
</RelativeLayout>


和Logcat:

10-04 22:48:47.884  27075-27075/com.sai.eventee E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.sai.eventee, PID: 27075
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sai.eventee/com.sai.eventee.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.jayfang.dropdownmenu.DropDownMenu.setmMenuCount(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2493)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555)
            at android.app.ActivityThread.access$800(ActivityThread.java:176)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437)
            at android.os.Handler.dispatchMessage(Handler.java:111)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5576)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.jayfang.dropdownmenu.DropDownMenu.setmMenuCount(int)' on a null object reference
            at com.sai.eventee.MainActivity.onCreate(MainActivity.java:90)
            at android.app.Activity.performCreate(Activity.java:6005)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2446)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555)
            at android.app.ActivityThread.access$800(ActivityThread.java:176)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437)
            at android.os.Handler.dispatchMessage(Handler.java:111)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5576)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)


我不知道为什么会得到一个空指针异常。

最佳答案

这意味着findViewById(R.id.activity_main_alternate)为mMenu返回null。您的activity_main_alternate.xml是否具有R.id.menu视图?

关于java - 尝试在空对象引用上调用虚拟方法'void com.jayfang.dropdownmenu.DropDownMenu.setmMenuCount(int)',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32935400/

10-10 16:06