AndroidでVolleyを使ってArrayListに要素を取得・表示する方法
はじめに
この記事では、AndroidアプリでVolleyライブラリを使ってサーバーからJSONデータを取得し、その結果をArrayList(配列リスト)に格納して画面に表示する方法を解説します。VolleyはGoogleが提供するHTTP通信ライブラリで、ネットワークリクエストの管理やレスポンスの処理をシンプルなコードで実現できるのが特徴です。
本チュートリアルでは、モックAPIからユーザーデータを取得し、「users」配列内の各ユーザーの「name」を抽出してArrayListに追加し、TextViewに一覧表示するサンプルアプリを作成します。
手順1:新規プロジェクトの作成
Android Studioを起動し、メニューからFile → New Projectを選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。
手順2:レイアウトファイル(activity_main.xml)の編集
res/layout/activity_main.xml に以下のコードを追加します。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
上記のコードでは、Volleyで取得したデータを表示するためのTextViewを1つ配置しています。ルートのLinearLayoutにcenterを指定しているため、テキストは画面中央に表示されます。
手順3:MainActivity.java の実装
src/MainActivity.java に以下のコードを追加します。
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
TextView textView;
RequestQueue queue;
String URL = "https://www.mocky.io/v2/597c41390f0000d002f4dbd1";
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
final List<String> list=new ArrayList<>();
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject object=new JSONObject(response);
JSONArray array=object.getJSONArray("users");
for(int i=array.length()-1;i>=0;i--) {
JSONObject object1=array.getJSONObject(i);
String name =object1.getString("name");
list.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
textView.setText(list.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
queue.add(request);
}
}
コードのポイント
- RequestQueueの生成:Volley.newRequestQueue(this)でリクエストキューを作成し、通信処理全体を管理します。
- StringRequestの送信:GETメソッドで指定したURLにアクセスし、レスポンスを文字列として受け取ります。
- JSONの解析:onResponse()の中でJSONObjectとJSONArrayを使ってレスポンスを解析し、「users」配列から各ユーザーのnameの値を取り出してArrayListに追加していきます。
- エラー処理:onErrorResponse()により、通信エラーが発生した場合にログへ詳細を出力します。
手順4:AndroidManifest.xml の編集
インターネット通信を行うため、AndroidManifest.xmlにINTERNETパーミッションを追加します。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
手順5:build.gradle の編集
アプリレベルのbuild.gradleに、Volleyライブラリを含む依存関係を追加します。
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
アプリの実行
それでは、アプリを実行してみましょう。ここでは、実際のAndroid端末をパソコンに接続しているものとします。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーのRun(実行)アイコンをクリックしてください。接続したモバイルデバイスを選択するとアプリが起動し、APIから取得したユーザー名のリストが画面に表示されます。

まとめ
Volleyを活用すれば、最小限のコードでHTTP通信とJSON解析を実装できます。取得したデータをArrayListに格納しておけば、ListViewやRecyclerViewなどの一覧表示コンポーネントとの連携も容易になり、実用的なアプリ開発につながります。ぜひ本サンプルをベースに、さまざまなAPI連携に挑戦してみてください。
-
AndroidでVolleyを使ってカスタムオブジェクトのArrayListを取得する方法【初心者向け解説】
この記事では、Androidアプリ開発においてVolleyライブラリを使ってサーバーから取得したJSONデータを、カスタムオブジェクト(UserInfoクラス)のArrayListに格納して扱う方法を解説します。ネットワーク通信の結果をオブジェクトとして管理したい場合に役立つテクニックです。 ステップ1:新規プロジェクトを作成する Android Studioを開き、「File」→「New Project」を選択して、必要な情報を入力し、新しいプロジェクトを作成します。 ステップ2:activity_main.xmlにコードを追加する res/layout/activity_main.xml
-
【Android開発】インストール済みアプリの一覧を取得して表示する方法
この記事では、Android端末にインストールされているアプリケーションの一覧を取得し、ListViewで画面に表示する方法を解説します。PackageManagerクラスを利用すれば、端末内のパッケージ情報に簡単にアクセスできるようになります。 手順1:新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目を入力して、新しいプロジェクトを作成してください。 手順2:レイアウトファイル(activity_main.xml)を編集する res/layout/activity_main.xml に以下のコードを