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());
}
try {
String api_url = "http://hoge.com/api/get_contents";
httpRequest(api_url);
} catch(Exception e) {
Log.e("エラー処理",e.getMessage());
}
Author And Source
この問題について(Androidアプリ(Java)から非同期でAPIを呼びJSONレスポンスをTextViewに表示させる方法), 我々は、より多くの情報をここで見つけました https://qiita.com/kenichiro-yamato/items/722fd329bd363b66f165著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .