Android application development 第33章:実践ミニアプリ:天気情報アプリ

🎯 この章の目的

「天気情報アプリ」という実用的な題材を通じて、次の技術要素を理解・体験します:

技術要素学習内容
RetrofitHTTP通信クライアントの基本的な使い方
GsonJSONをJavaオブジェクトへパース
ViewModelUIとロジックの分離
LiveDataUIへの非同期データ反映
エラーハンドリング通信失敗やAPI異常時の対応

🌤 アプリの構成

  • 画面:都市名を入力 → 検索ボタン → 天気情報を表示
  • データ取得:OpenWeatherMap APIなどを呼び出し
  • 構成要素
    • MainActivity:UIを管理
    • WeatherViewModel:UIとデータ取得処理をつなぐ
    • WeatherRepository:API呼び出しと結果整形
    • RetrofitService:API通信定義
    • Gson:JSONをJavaオブジェクトへ変換

🧩 Retrofitを用いたAPI通信

Step 1:Retrofitインタフェースの定義

public interface WeatherApiService {
    @GET("weather")
    Call<WeatherResponse> getWeather(
        @Query("q") String cityName,
        @Query("appid") String apiKey,
        @Query("units") String units
    );
}

Step 2:Retrofitインスタンスの作成

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.openweathermap.org/data/2.5/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

WeatherApiService service = retrofit.create(WeatherApiService.class);

☁ JSONパース(Gson)

Retrofitと組み合わせて、JSONレスポンスを自動でJavaクラスに変換します。

{
  "weather": [ { "main": "Clear", "description": "clear sky" } ],
  "main": { "temp": 27.5 }
}

それに対応するJavaクラス:

public class WeatherResponse {
    public List<Weather> weather;
    public Main main;

    public static class Weather {
        public String main;
        public String description;
    }

    public static class Main {
        public float temp;
    }
}

🧠 ViewModelの活用

ViewModelで非同期処理を扱い、UIとの分離を実現します。

public class WeatherViewModel extends ViewModel {
    private final MutableLiveData<WeatherResponse> weatherData = new MutableLiveData<>();
    private final MutableLiveData<String> error = new MutableLiveData<>();

    public void fetchWeather(String city) {
        WeatherApiService service = RetrofitClient.getInstance().create(WeatherApiService.class);
        service.getWeather(city, "your_api_key", "metric").enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
                if (response.isSuccessful()) {
                    weatherData.postValue(response.body());
                } else {
                    error.postValue("都市が見つかりません");
                }
            }

            @Override
            public void onFailure(Call<WeatherResponse> call, Throwable t) {
                error.postValue("通信に失敗しました:" + t.getMessage());
            }
        });
    }

    public LiveData<WeatherResponse> getWeatherData() { return weatherData; }
    public LiveData<String> getError() { return error; }
}

🎛 MainActivityのUI連携例

viewModel.getWeatherData().observe(this, data -> {
    tempText.setText(data.main.temp + "°C");
    descText.setText(data.weather.get(0).description);
});

viewModel.getError().observe(this, errorMsg -> {
    Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
});

🚨 エラーハンドリングのポイント

ケース対応方法
ネットワーク接続エラーonFailure() で検知し、ユーザーに通知
APIレスポンスが404response.isSuccessful() で検知し、メッセージ表示
JSON構造変更Gsonでのマッピング失敗に備えて例外補足

🔄 全体の流れ(図解)


💡 まとめ

このミニアプリでは、次のような重要なAndroid開発スキルを学びます:

  • HTTP通信(非同期)の実装
  • JSON → Javaオブジェクトの変換(Gson)
  • UIとロジックの分離(ViewModel)
  • エラー時のユーザー対応

Javaエンジニアの視点からすると、Retrofitは「JAX-RS + Jackson」のような役割を果たしており、ViewModelはMVCのControllerに近い感覚です。
しかし、非同期性ライフサイクル対応の点で、Androidならではのアプローチを取る必要があります。

mh

Related Posts

Android application development 第32章:実践ミニアプリ:シンプルなToDoリスト

Android application development 第31章:Firebase Analytics や Remote Config の活用

You Missed

Google Cloud Platform エンジニア向け教科書:実践から認定まで : 第4章:課金と料金モデル、予算とアラート:GCPの「お財布」管理術

  • 投稿者 mh
  • 6月 3, 2025
  • 5 views

Kubernetes Learning 第30章:NetworkPolicyの使い方 〜Pod間通信を制御するセキュリティの要〜

  • 投稿者 mh
  • 6月 3, 2025
  • 5 views

Google Cloud Platform エンジニア向け教科書:実践から認定まで : 第3章:IAM(Identity and Access Management):GCPの「誰が」「何に」「何ができるか」を管理する門番

  • 投稿者 mh
  • 6月 2, 2025
  • 16 views

現場で使えるChrome DevTools実践ガイド 第9章:Applicationパネルとストレージの確認

  • 投稿者 mh
  • 6月 2, 2025
  • 12 views

Kubernetes Learning 第29章:RBACの基礎とロール設計 〜「誰が、何を、どこで」できるのかを制御する〜

  • 投稿者 mh
  • 6月 2, 2025
  • 14 views

Android application development 第33章:実践ミニアプリ:天気情報アプリ

  • 投稿者 mh
  • 6月 2, 2025
  • 14 views