NPE while using HashMap to populate ListView

百般思念 提交于 2020-01-17 04:56:09

问题


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) 

回答1:


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);



回答2:


I think you should initialize the adapter first and then pass it to setadapter.

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


来源:https://stackoverflow.com/questions/36571025/npe-while-using-hashmap-to-populate-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!