NPE,同时使用HashMap来填充ListView [英] NPE while using HashMap to populate ListView

查看:145
本文介绍了NPE,同时使用HashMap来填充ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一家餐馆创建一个Android应用程序,让服务员接受客户的订单。我正在使用扩展列表视图来显示菜单并使用散列表来填充扩展列表视图。当我运行该应用程序时,没有任何错误,但尝试使用扩展列表视图打开活动时应用程序崩溃。调试后,我发现有空指针异常导致它崩溃,但我努力修复它。
以下是我的代码:

菜单活动:

  public class Menu extends AppCompatActivity {

HashMap< String,List< String>>菜单;
列表< String> Food_list;
ExpandableListView Exp_list;
FoodMenuAdapter适配器;


@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


Exp_list =(ExpandableListView)findViewById(R.id.exp_list);
Food_menu = DataProvider.getInfo();
Food_list = new ArrayList< String>(Food_menu.keySet());
Exp_list.setAdapter(adapter);
adapter = new FoodMenuAdapter(this,Food_menu,Food_list);


Exp_list.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener(){
@Override
public void onGroupExpand(int groupPosition)
{
Toast pass2 = Toast.makeText(getBaseContext(),Food_list.get(groupPosition)+is Expanded,Toast.LENGTH_SHORT);
pass2.show();;
}
});






食品菜单适配器类:


  public class FoodMenuAdapter extends BaseExpandableListAdapter {

private Context ctx;
私有HashMap< String,List< String>> Food_Category;
私人列表< String> Food_List;

public FoodMenuAdapter(Context ctx,HashMap< String,List< String>>> Food_Category,List< String> Food_List)
{
this.ctx = ctx;
this.Food_Category = Food_Category;
this.Food_List = Food_List;


$ b @覆盖
public int getGroupCount()
{
return Food_List.size();
}

@Override
public int getChildrenCount(int arg0)
{
return Food_Category.get(Food_List.get(arg0))size( );
}

@Override
public Object getGroup(int arg0)
{
return Food_List.get(arg0);

$ b @Override
public Object getChild(int parent,int child)
{
return Food_Category.get(Food_List.get(parent))获得(孩子);
}

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

@Override
public long getChildId(int parent,int child)
{
return child;
}

@Override
public boolean hasStableIds(){
return false;

$ b @Override
public View getGroupView(int parent,boolean isExpanded,View convertView,ViewGroup parentView)
{
String group_title =(String) getGroup(父);
if(convertView == null)
{
LayoutInflater infalter =(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalter.inflate(R.layout.parent_layout,parentView,false);
}
TextView parent_textview =(TextView)convertView.findViewById(R.id.parent_txt);
parent_textview.setTypeface(null,Typeface.BOLD);
parent_textview.setText(group_title);
返回convertView;

$ b @Override
public View getChildView(int parent,int child,boolean lastChild,View convertView,ViewGroup parentView)
{
String child_title = (String)getChild(parent,child);
if(convertView == null)
{
LayoutInflater inflater =(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_layout,parentView,false);

}

TextView child_textview =(TextView)convertView.findViewById(R.id.child_txt);
child_textview.setText(child_title);

返回convertView;

$ b @Override
public boolean isChildSelectable(int groupPosition,int childPosition)
{
return true;


$ / code $ / pre

DataProvider Class:

  public class DataProvider {

public static HashMap< String,List< String>> getInfo(){
HashMap< String,List< String>> FoodDetails = new HashMap< String,List< String>>();

列表< String> Starter_Menu = new ArrayList< String>();
Starter_Menu.add(Cheesy Garlic Bread);
Starter_Menu.add(肝酱);
Starter_Menu.add(每日汤);
Starter_Menu.add(凯撒沙拉);
Starter_Menu.add(虾鸡尾酒);

列表< String> Main_Menu = new ArrayList< String>();
Main_Menu.add(Steak Burger);
Main_Menu.add(牛肋骨);
Main_Menu.add(10oz Steak);
Main_Menu.add(Pappardelle Pasta);
Main_Menu.add(鱼和薯条);

列表< String> Desstert_Menu = new ArrayList< String>();
Desstert_Menu.add(Sticky Toffee Pudding);
Desstert_Menu.add(巧克力布朗尼冰淇淋);
Desstert_Menu.add(芝士蛋糕);
Desstert_Menu.add(冰淇淋);
Desstert_Menu.add(草莓酥皮);

列表< String> Sides_Menu = new ArrayList< String>();
Sides_Menu.add(洋葱圈);
Sides_Menu.add(芯片);
Sides_Menu.add(大蒜面包);
Sides_Menu.add(大蒜土豆);
Sides_Menu.add(烟草洋葱);

列表< String> Drinks_Menu = new ArrayList< String>();
Drinks_Menu.add(Tennants);
Drinks_Menu.add(可乐);
Drinks_Menu.add(红酒);
Drinks_Menu.add(白葡萄酒);
Drinks_Menu.add(Guiness);
Drinks_Menu.add(Magners);

FoodDetails.put(Starter Menu,Starter_Menu);
FoodDetails.put(主菜单,Main_Menu);
FoodDetails.put(Dessert Menu,Desstert_Menu);
FoodDetails.put(Sides Menu,Sides_Menu);
FoodDetails.put(Drinks Menu,Drinks_Menu);

返回FoodDetails;




$ b $ p
$ b

它在菜单活动中说Exp_list,Food_menu和Food_list全部为空。有没有人看到问题或知道如何解决它?

编辑



已添加Logcat

  04-12 10:56:45.177 1984-1984 / com.example.ben.restaurantapp E / AndroidRuntime:FATAL EXCEPTION:main 
过程:com.example.ben.restaurantapp, PID:1984
java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.ben.restaurantapp / com.example.ben.restaurantapp.Menu}:java.lang.NullPointerException:试图调用虚拟方法'无效android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)'上的空对象引用
在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
在android.app.ActivityThread .handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access $ 800(ActivityThread.java:144)
at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Loo per.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
在java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899)
at com。 android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
导致:java.lang.NullPointerException:试图调用虚拟方法'void android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter) '在空对象引用
at com.example.ben.restaurantapp.Menu.onCreate(Menu.java:39)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread .java:2360)
at和roid.app.ActivityThread.access $ 800(ActivityThread.java:144)
at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler .java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java。 lang.reflect.Method.invoke(Native方法)$ b $在java.lang.reflect.Method.invoke(Method.java:372)
在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)


解决方案

一个问题可能是您在设置适配器后初始化适配器,并且其中的所有项都为空

  Exp_list.setAdapter(adapter); 
adapter = new FoodMenuAdapter(this,Food_menu,Food_list);

这可以解决问题:

  adapter = new FoodMenuAdapter(this,Food_menu,Food_list); 
Exp_list.setAdapter(adapter);


I am creating an android app for a restaurant that lets the waiters take the customers orders. I am using a extended list view to show the menu and have used a hashmap to populate the extended list view. When I run the app, there are no errors but the app crashes when trying to open the activity with the extended list view on it. After debugging, I found that there were null pointer exceptions causing it to crash but I'm struggling to fix it. Below is my code:

Menu activity:

public class Menu extends AppCompatActivity {

    HashMap<String, List<String >> Food_menu;
    List<String> Food_list;
    ExpandableListView Exp_list;
    FoodMenuAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Exp_list = (ExpandableListView) findViewById(R.id.exp_list);
        Food_menu = DataProvider.getInfo();
        Food_list = new ArrayList<String>(Food_menu.keySet());
        Exp_list.setAdapter(adapter);
        adapter = new FoodMenuAdapter(this, Food_menu, Food_list);


        Exp_list.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition)
            {
                Toast pass2 = Toast.makeText(getBaseContext(),Food_list.get(groupPosition) + "is Expanded", Toast.LENGTH_SHORT);
                pass2.show();;
            }
        });


    }
}

FoodMenuAdapter Class:

public class FoodMenuAdapter  extends BaseExpandableListAdapter{

    private Context ctx;
    private HashMap<String, List<String>> Food_Category;
    private List<String> Food_List;

    public FoodMenuAdapter(Context ctx, HashMap<String, List<String>> Food_Category, List<String> Food_List)
    {
        this.ctx = ctx;
        this.Food_Category = Food_Category;
        this.Food_List = Food_List;
    }


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

    @Override
    public int getChildrenCount(int arg0)
    {
        return Food_Category.get(Food_List.get(arg0)).size();
    }

    @Override
    public Object getGroup(int arg0)
    {
        return Food_List.get(arg0);
    }

    @Override
    public Object getChild(int parent, int child)
    {
        return Food_Category.get(Food_List.get(parent)).get(child);
    }

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

    @Override
    public long getChildId(int parent, int child)
    {
        return child;
    }

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

    @Override
    public View getGroupView(int parent, boolean isExpanded, View convertView, ViewGroup parentView)
    {
        String group_title = (String) getGroup(parent);
        if (convertView == null)
        {
            LayoutInflater infalter = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalter.inflate(R.layout.parent_layout, parentView, false);
        }
        TextView parent_textview = (TextView) convertView.findViewById(R.id.parent_txt);
        parent_textview.setTypeface(null, Typeface.BOLD);
        parent_textview.setText(group_title);
        return convertView;
    }

    @Override
    public View getChildView(int parent, int child, boolean lastChild, View convertView, ViewGroup parentView)
    {
        String child_title = (String) getChild(parent, child);
        if(convertView == null)
        {
            LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.child_layout, parentView, false);

        }

        TextView child_textview = (TextView) convertView.findViewById(R.id.child_txt);
        child_textview.setText(child_title);

        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition)
    {
        return true;
    }
}

DataProvider Class:

public class DataProvider {

    public static HashMap<String, List<String>> getInfo() {
        HashMap<String, List<String>> FoodDetails = new HashMap<String, List<String>>();

        List<String> Starter_Menu = new ArrayList<String>();
        Starter_Menu.add("Cheesy Garlic Bread");
        Starter_Menu.add("Liver Pate");
        Starter_Menu.add("Soup of the Day");
        Starter_Menu.add("Caesar Salad");
        Starter_Menu.add("Prawn Cocktail");

        List<String> Main_Menu = new ArrayList<String>();
        Main_Menu.add("Steak Burger");
        Main_Menu.add("Rib of Beef");
        Main_Menu.add("10oz Steak");
        Main_Menu.add("Pappardelle Pasta");
        Main_Menu.add("Fish and Chips");

        List<String> Desstert_Menu = new ArrayList<String>();
        Desstert_Menu.add("Sticky Toffee Pudding");
        Desstert_Menu.add("Chocolate Brownee with Ice Cream");
        Desstert_Menu.add("Cheesecake");
        Desstert_Menu.add("Ice Cream");
        Desstert_Menu.add("Strawberry Meringue");

        List<String> Sides_Menu = new ArrayList<String>();
        Sides_Menu.add("Onion Rings");
        Sides_Menu.add("Chips");
        Sides_Menu.add("Garlic Bread");
        Sides_Menu.add("Garlic Potatoes");
        Sides_Menu.add("Tobacco Onions");

        List<String> Drinks_Menu = new ArrayList<String>();
        Drinks_Menu.add("Tennants");
        Drinks_Menu.add("Coke");
        Drinks_Menu.add("Red Wine");
        Drinks_Menu.add("White Wine");
        Drinks_Menu.add("Guiness");
        Drinks_Menu.add("Magners");

        FoodDetails.put("Starter Menu", Starter_Menu);
        FoodDetails.put("Main Menu", Main_Menu);
        FoodDetails.put("Dessert Menu", Desstert_Menu);
        FoodDetails.put("Sides Menu", Sides_Menu);
        FoodDetails.put("Drinks Menu", Drinks_Menu);

        return FoodDetails;
    }
}

It says in the Menu Activity that Exp_list, Food_menu and Food_list are all null. Does anyone see the problem or know how to fix it?

Edit

Logcat has been added

04-12 10:56:45.177 1984-1984/com.example.ben.restaurantapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ben.restaurantapp, PID: 1984
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ben.restaurantapp/com.example.ben.restaurantapp.Menu}: 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:2298)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    at android.app.ActivityThread.access$800(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    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:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
    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.example.ben.restaurantapp.Menu.onCreate(Menu.java:39)
    at android.app.Activity.performCreate(Activity.java:5937)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    at android.app.ActivityThread.access$800(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    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:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 

解决方案

One problem could be that you're initializing the adapter after you set it and all items in it are null

Exp_list.setAdapter(adapter);
adapter = new FoodMenuAdapter(this, Food_menu, Food_list);

This might solve the problem:

adapter = new FoodMenuAdapter(this, Food_menu, Food_list);
Exp_list.setAdapter(adapter);

这篇关于NPE,同时使用HashMap来填充ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆