2016-10-25

In the last few posts, we have executed material navigation drawer with or without using the design support library where items of the navigation drawer were static, that is, they were predefined.
In any case, there are times when you need things to change as indicated by certain client activities or prefrences. In this post, we will progressively add things to a navigation drawer from a database with design support library, MySQLi and PHP scripts.



1)Creating some database tables:
This should always be the very first step whenever there’s a database involved. Here, we create a demo database hosted locally via Apache Web Server using XAMPP to serve the purpose of this post. For XAMPP – https://www.apachefriends.org/index.html.
Below is the screenshot of a demo table  – ‘test‘ – just holding some string values in column ‘Items‘.



2)PHP Script:
Here, We return a JSON response containing names of all the great houses from ASOIAF as declared in the above table.

getItems.php

The response from the above script:
[“House Lannister”,”House Stark”,”House Targaryen”,”House Martell”,”House Tyrell”,”House Tully”]

3)Include Desing Support Library Dependency:
Now, fire up the Android Studio, select an ‘EMPTY‘ activity and include the design support library in your Gradle. Open Module(App) Gradle file and add the below dependencies. (If prompted update your android SDK).

4)Creating a Blank Menu Resource:

Create a new Android Resouce Directory of resource type ‘menu‘ in res and name it ‘menu‘.

Create a new menu resource file – ‘drawer_menu.xml‘ in the menu directory.

This blank menu is attached with navigationalView to inflate menu items. We will programmatically add items to this menu later in this post.

5)Modifying Styles:
Open your style.xml file from the values directory and change the parent theme to ‘Theme.AppCompat.NoActionBar’ since we will be implementing a toolbar.

styles.xml

6)Adding the internet permission:
Open up your AndroidManifest.xml file and add

above the application declaration.

7)Designing the Navigation Drawer:
Navigation View inflates navigation items from a menu resource. The hierarchy of elements is shown below:



Basically, a DrawerLayout holds two items – one is the NavigationView and the other Container view.
Container view includes a frameLayout to inflate fragment view and a toolbar. The app: menu attribute of navigation view refers to the blank menu resource created above.

activity_main.xml

6)Retrieving required data from the database.
Now the thing is: To dynamically add navigation items, we first get all the elements to be inflated from the database and then add those to the menu by passing our menu as a parameter to an async task.
Here, JsonReader is used to parse the response from the PHP script.

MainActivity.java

Hope you enjoy this tutorial and if it useful for you and want some more interesting article then subscribe us.

Show more