Search code examples
androidmenuitemandroid-navigationview

Android : add menuItem in NavigationView pragmatically from webservice


In NavigationView of my app has several menus but I wanted to user only access particular menus. According to user privilege user will able to view only his accessible menus. So I created webservice which return me list of menus.

Here is json output of menu access

[
  {
    "id": "1",
    "appId": "1",
    "userId": "1",
    "name": "Design List",
    "icon": "http://some_website/Demo/images/menu/1.png",
    "code": "dsn001"
  },
  {
    "id": "2",
    "appId": "1",
    "userId": "1",
    "name": "Price List",
    "icon": "http://some_website/Demo/images/menu/2.png",
    "code": "prc002"
  },
  ....]

For example user has only access to this menus. I have a navigationview ready in application. I wanted to add this menus to navigationview.

In android I created a model class for menu

MenuItems.java

public class MenuItems {

    public String id;
    public String appId;
    public String userId;
    public String name;
    public String icon;
    public String code;
}

In webservice response, I converted response to ArrayList<MenuItems>() here is webservice code.

ArrayList<MenuItems> menuItem = new ArrayList<MenuItems>();
.
.
MenuItems[] items = new Gson().fromJson(response, MenuItems[].class);
for (MenuItems m : items) {
    menuItem.add(m);
}

In main activity I did this code.

Menu menu = navigationView.getMenu();
    if (menuList != null) {
        for (MenuItems items : menuList) {
            MenuItem menuItem = menu.add(items.name);
            menuItem.setIcon(new BitmapDrawable(items.icon));
        }
    }

But still it didn't work.

I wanted display this menus with icon in navigationview. can we show icon using Picaso library? please help.


Solution

  • For adding Navigation menuItems Dynamically, you should get the Menu object from the NavigationView at run time like this. also fetch the icons from the server and keep it.

        Menu menu = navigationView.getMenu();
    

    then add the List of menu to it

        for (MenuItems item : items) {
            MenuItem lNavigationMenuItem = menu.add(groupId, itemId, order, title);
            //fetch the bitmap from the server asynchronously before and add it to the menu as follows 
            lNavigationMenuItem.setIcon(new BitmapDrawable(bitmap));
        }