Intermediate: Network Management (URL Using a Data Network) in Harmony OS
Huawei provides various services for developers to make ease of development and provides best user experience to end users. In this article, we will cover Network Management with Java in Harmony OS.
In this article, we are going to learn how to fetch data from Rest APIs and display in List container in Harmony OS. Also we will learn how to parse easy and efficient way json result using Gson library.
The list of methods available in the APIs for opening a URL using a data network as follows:
You need to install DevEcho studio IDE and I assume that you have prior knowledge about the Harmony OS and java.
- A computer (desktop or laptop) running Windows 10.
- A Huawei phone (with the USB cable), which is used for debugging.
- Java JDK installation package.
- DevEcho studio installed.
Follows the steps.
1. Create HarmonyOS Project.
- Open DevEcho studio.
- Click NEW Project, select a Project Templet.
- Select ability template and click Next as per below image.
Enter Project and Package Name and click on Finish.
2. Once you have created the project, DevEco Studio will automatically sync it with Gradle files. Find the below image after synchronization is successful.
3. Update Permission and app version in config.json file as per your requirement, otherwise retain the default values. To use the functions of the network management module, you must obtain the below permissions.
4. Create New Ability, as follows.
5. Development Procedure.
Create MainAbilitySlice.java ability and add the below code.
Create ability_main.xml layout and add the below code.
Create UserDAO.java model class and add the below code, and add parameters as per APIs result.
Create NMItemProvider.java ability and add the below code.
Create user_list_item.xml layout and add the below code.
6. To build apk and run in device, choose Build > Generate Key and CSR Build for Hap(s)\ APP(s) or Build and Run into connected device, follow the steps.
Run Apk into emulator or connected device its will fetch data as per below images.
Tips and Tricks
- Always use the latest version of DevEcho Studio.
- Use Harmony Device Simulator from HVD section.
- Network task or any long running task should run in background thread.
- Make sure network permissions added into config.json file.
In this article, we have learnt to fetch data from Rest APIs and show into list container in Harmony OS. Gson library used to convert a JSON string to an equivalent Java object easy and efficient way. Also we have used Task Dispatcher which help us to run network task in background thread and update UI in UI Thread.
Thanks for reading the article, please do like and comment your queries or suggestions.