Androidアプリ(Java)から非同期でAPIを呼びJSONレスポンスをTextViewに表示させる方法


やりたいこと

JavaでのAndroidアプリ開発にて。
メインスレッドからAPIを非同期で呼び、
APIのJSONレスポンス(に含まれる文字列)を、
UI(ビュー)に表示させたい。

前提

  • APIへアクセスできる設定(Manifestなど)が完了していること。
  • OkHttpClientが使える状態であること。

実装

たとえば MainActivity にて、下記のようなメソッドを実装する。

    /**
     * http(s)で始まる、APIのURLを文字列(String)で受け取り、
     * APIにアクセスしてJSONレスポンスを取得し、メインスレッドのUIを更新する。
     */
    void httpRequest(String url) throws IOException
    {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        Log.e("onFailure", e.getMessage());
                    }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        final String jsonStr = response.body().string();
                        try {
                            JSONObject json = new JSONObject(jsonStr);
                            final String name = json.getString("name");
                            Handler mainHandler = new Handler(Looper.getMainLooper());
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    TextView textView = (TextView)findViewById(R.id.hoge);
                                    textView.setText(name);
                                }
                            });
                        } catch(Exception e) {
                            Log.e("Exception", e.getMessage());
                        }
                    }
                });
    }

呼び出し方

try {
    String api_url = "http://hoge.com/api/get_contents";
    httpRequest(api_url);
} catch(Exception e) {
    Log.e("エラー処理",e.getMessage());
}