(4)在界面中调用 API

在 MainAbilitySlice 中调用 API 并显示营养数据。

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.agp.components.TextInput;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import java.io.IOException;

public class MainAbilitySlice extends AbilitySlice {
    private TextInput inputFoodItem;
    private Button btnSearch;
    private Text textNutritionData;
    private EdamamService edamamService;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        inputFoodItem = (TextInput) findComponentById(ResourceTable.Id_input_food_item);
        btnSearch = (Button) findComponentById(ResourceTable.Id_btn_search);
        textNutritionData = (Text) findComponentById(ResourceTable.Id_text_nutrition_data);
        edamamService = new EdamamService();

        btnSearch.setClickedListener(component -> {
            String foodItem = inputFoodItem.getText();
            edamamService.getNutritionData(foodItem, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    getUITaskDispatcher().asyncDispatch(() ->
                        textNutritionData.setText("Error: " + e.getMessage())
                    );
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        NutritionData nutritionData = NutritionData.fromJson(response);
                        getUITaskDispatcher().asyncDispatch(() ->
                            textNutritionData.setText(nutritionData.toString())
                        );
                    } catch (JSONException e) {
                        getUITaskDispatcher().asyncDispatch(() ->
                            textNutritionData.setText("Error parsing data")
                        );
                    }
                }
            });
        });
    }
}

(5)更新界面布局 (ability_main.xml)

添加输入框和显示营养数据的组件。

<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_parent"
    ohos:orientation="vertical"
    ohos:padding="20vp">

    <TextInput
        ohos:id="$+id:input_food_item"
        ohos:width="match_parent"
        ohos:height="wrap_content"
        ohos:hint="Enter a food item"
        ohos:margin_top="10vp"/>

    <Button
        ohos:id="$+id:btn_search"
        ohos:width="match_parent"
        ohos:height="wrap_content"
        ohos:text="Search Nutrition Data"
        ohos:margin_top="10vp"/>

    <Text
        ohos:id="$+id:text_nutrition_data"
        ohos:width="match_parent"
        ohos:height="wrap_content"
        ohos:text="Nutrition data will appear here"
        ohos:text_size="18fp"
        ohos:margin_top="20vp"/>
</DirectionalLayout>

运行 HTML


4. 测试 API 集成

  1. 运行应用,输入食物名称(如 "1 apple")。

  2. 点击搜索按钮,查看返回的营养数据。


5. 后续优化

  • 缓存数据:将常用的食物营养数据缓存到本地数据库,减少 API 调用。

  • 错误处理:增加网络错误和 API 错误的处理逻辑。

  • 用户历史:保存用户的搜索记录和营养数据。 

总之本期教程就到这里,后续会通过鸿蒙开发环境进行详细分析,大家可以把遇到的问题进行评论区讨论! 

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐