java - 设置适配器空指针

标签 java android

我已经尝试解决一个问题几个小时了,但我没能弄清楚。我尝试为可扩展 ListView 设置适配器,但出现此错误。谢谢。 “尝试在空对象引用上调用虚拟方法 'void android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)'”

Main_Activity

 public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button b1;


    private ResideMenu resideMenu;
    private Context mContext;
    private ResideMenuItem itemAnasayfa;
    private ResideMenuItem itemRastgele;
    private ResideMenuItem itemEncok;
    private ResideMenuItem itemTarifyaz;

    private ExpandableListView listView;
    private ExpandableListAdapter listAdapter;
    private List<String> listDataHeader;
    private HashMap<String,List<String>> listHash;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        listView=(ExpandableListView)findViewById(R.id.exp2);
        initData();
        listAdapter=new com.yeni.ExpandableListAdapter(this,listDataHeader,listHash);
        listView.setAdapter(listAdapter);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        setUpMenu();
        if (savedInstanceState == null) {

            changeFragment(new F_ana_sayfa());

        }

    }

    private void initData() {
        listDataHeader=new ArrayList<>();
        listHash=new HashMap<>();

        listDataHeader.add("et");
        listDataHeader.add("tavuk");
        listDataHeader.add("sebze");
        listDataHeader.add("diger");

        List<String> l_et=new ArrayList<>();
        l_et.add("kemikli");
        l_et.add("kuşbaşı");

        List<String> l_tavuk=new ArrayList<>();
        l_tavuk.add("bonfile");
        l_tavuk.add("but");
        l_tavuk.add("bütün tavuk");

        List<String> l_sebze=new ArrayList<>();
        l_sebze.add("patates");
        l_sebze.add("biber");
        l_sebze.add("kabak");
        l_sebze.add("patlıcan");

        List<String> l_diger=new ArrayList<>();
        l_diger.add("tuz");
        l_diger.add("yağ");
        l_diger.add("kekik");

        listHash.put(listDataHeader.get(0),l_et);
        listHash.put(listDataHeader.get(1),l_tavuk);
        listHash.put(listDataHeader.get(2),l_sebze);
        listHash.put(listDataHeader.get(3),l_diger);

    }

    private void setUpMenu() {
        resideMenu = new ResideMenu(this);
        resideMenu.setBackground(R.drawable.menu_background);
        resideMenu.attachToActivity(this);


        resideMenu.setMenuListener(menuListener);
        resideMenu.setScaleValue(0.6f);
        //create menu items;
        itemAnasayfa = new ResideMenuItem(this, R.drawable.icon_home, "Ana Sayfa");
        itemRastgele = new ResideMenuItem(this, R.drawable.icon_profile, "Random tarif bul");
        itemEncok = new ResideMenuItem(this, R.drawable.icon_calendar, "En cok begenilenler");
        itemTarifyaz = new ResideMenuItem(this, R.drawable.icon_settings, "tarif Yaz");


        itemAnasayfa.setOnClickListener(this);
        itemRastgele.setOnClickListener(this);
        itemEncok.setOnClickListener(this);
        itemTarifyaz.setOnClickListener(this);


        resideMenu.addMenuItem(itemAnasayfa, ResideMenu.DIRECTION_LEFT);
        resideMenu.addMenuItem(itemRastgele, ResideMenu.DIRECTION_LEFT);
        resideMenu.addMenuItem(itemEncok, ResideMenu.DIRECTION_RIGHT);
        resideMenu.addMenuItem(itemTarifyaz, ResideMenu.DIRECTION_RIGHT);

        findViewById(R.id.title_bar_left_menu).setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
            }
        });

        findViewById(R.id.title_bar_right_menu).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
            }
        });
    }

    @Override

    public boolean dispatchTouchEvent(MotionEvent ev) {
        return resideMenu.dispatchTouchEvent(ev);
    }

    @Override
    public void onClick(View view) {

        if (view == itemAnasayfa) {
            changeFragment(new F_ana_sayfa());
        } else if (view == itemRastgele) {
            changeFragment(new F_rastgele_tarif());
        } else if (view == itemEncok) {
            changeFragment(new F_encok_beg());
        } else if (view == itemTarifyaz) {
            changeFragment(new F_tarif_yaz());
        }
        else
            changeFragment(new F_ana_sayfa());


        resideMenu.closeMenu();
    }


    private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
        @Override
        public void openMenu() {
            Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void closeMenu() {

            Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
        }


    };




    private void changeFragment(Fragment targetFragment) {
        resideMenu.clearIgnoredViewList();
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.main_fragment, targetFragment, "fragment")
                .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                .commit();
    }

    public ResideMenu getResideMenu(){
        return resideMenu;}
}

适配器类

    public class ExpandableListAdapter extends BaseExpandableListAdapter {

    private Context cont;
    private List<String> listDataHeader;
    private HashMap<String,List<String>> listHashMap;

    public ExpandableListAdapter(Context cont, List<String> listDataHeader, HashMap<String, List<String>> listHashMap) {
        this.cont = cont;
        this.listDataHeader = listDataHeader;
        this.listHashMap = listHashMap;
    }

    @Override
    public int getGroupCount() {
        return listDataHeader.size();
    }

    @Override
    public int getChildrenCount(int i) {
        return listHashMap.get(listDataHeader.get(i)).size();
    }

    @Override
    public Object getGroup(int i) {
        return listDataHeader.get(i);
    }

    @Override
    public Object getChild(int i, int i1) { // i=group position i=item position
        return listHashMap.get(listDataHeader.get(i)).get(i1);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
        String headerTitle=(String)getGroup(i);

        if (view==null){
            LayoutInflater inflater1=(LayoutInflater)this.cont.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view=inflater1.inflate(R.layout.list_group,null);

        }

        TextView lblHeader=(TextView)view.findViewById(R.id.header);
        lblHeader.setTypeface(null, Typeface.BOLD);
        lblHeader.setText(headerTitle);
        return view;
    }

    @Override
    public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
        final String childText=(String)getChild(i,i1);

        if (view==null){
            LayoutInflater inflater1=(LayoutInflater)this.cont.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view=inflater1.inflate(R.layout.list_item,null);

        }

        TextView txtListChild=(TextView)view.findViewById(R.id.list_item);
        txtListChild.setText(childText);
        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }
}

Activity_Main XML

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:background="@android:color/white"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ExpandableListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/exp2" />

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/layout_top">

            <!--<ImageView-->
                <!--android:layout_width="match_parent"-->
                <!--android:layout_height="3dp"-->
                <!--android:background="#2ea3fe"/>-->

            <FrameLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

                <Button
                    android:layout_width="28dp"
                    android:layout_height="28dp"
                    android:background="@drawable/titlebar_menu_selector"
                    android:id="@+id/title_bar_left_menu"
                    android:layout_gravity="left|center_vertical"
                    android:layout_marginLeft="10dp"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="7dp"
                    android:text="Yemek Do"
                    android:textSize="24sp"
                    android:layout_gravity="center"
                    android:textColor="?attr/actionModeSplitBackground" />

                <Button
                    android:layout_width="28dp"
                    android:layout_height="28dp"
                    android:background="@drawable/titlebar_menu_selector"
                    android:id="@+id/title_bar_right_menu"
                    android:layout_gravity="right|center_vertical"
                    android:layout_marginRight="10dp"/>
            </FrameLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="5dp"
                android:background="#bcb8b8"/>

        </LinearLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:id="@+id/main_fragment">

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

                <Button
                    android:text="Button"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true"
                    android:layout_marginLeft="107dp"
                    android:layout_marginStart="107dp"
                    android:layout_marginTop="188dp"
                    android:id="@+id/button2" />

                <Button
                    android:text="Button"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_alignRight="@+id/button2"
                    android:layout_alignEnd="@+id/button2"
                    android:layout_marginTop="78dp"
                    android:id="@+id/button3" />
            </RelativeLayout>
        </FrameLayout>

    </LinearLayout></code></pre>
</div>
</div>

list_group.xml

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

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/header" />
    </LinearLayout>

list_item.xml

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

    <TextView
        android:text="TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list_item" />
</LinearLayout>

错误日志

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.yeni, PID: 2404 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yeni/com.yeni.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)' on a null object reference at com.yeni.MainActivity.onCreate(MainActivity.java:55) at android.app.Activity.performCreate(Activity.java:6662) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6077)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

最佳答案

你在做什么:

 listView=(ExpandableListView)findViewById(R.id.exp2);
initData();
listAdapter=new com.yeni.ExpandableListAdapter(this,listDataHeader,listHash);
listView.setAdapter(listAdapter);

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

在 setContentView 之前初始化 listview 对象是错误的。应该是这样的

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ExpandableListView)findViewById(R.id.exp2);
initData();
listAdapter=new 
          com.yeni.ExpandableListAdapter(this,listDataHeader,listHash);
listView.setAdapter(listAdapter);

关于java - 设置适配器空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43279587/

相关文章:

java - Sonar 时间范围之间的代码行

java - 第一个 Activity 仅适用于我的 Android 项目

java - characteristic.getDescriptor() 返回 null

java - 如何在AsyncTask中启动客户端并连接到服务器?

android - 使用 Android DefaultHTTPClient 执行 POST 请求会导致 execute() 卡住

java - 创建泛型类以传递泛型类型(对象或列表)

java - 数据库函数与其他列的Hibernate/JPA属性映射结果

android - android中的中间件是什么?

java - 使用正则表达式匹配字符串的开头和结尾[Java]

android - 抑制 Gradle 弃用警告