AndroidでJSON配列を逆順に読み取る方法|サンプルコード付きで解説
AndroidでJSON配列を逆順に読み取る方法
本記事では、Androidアプリでネットワークから取得したJSON配列を、末尾の要素から先頭に向かって逆順に読み取る方法を解説します。HTTP通信にはGoogle製のHTTPライブラリ「Volley」を使用し、取得したレスポンスはorg.jsonパッケージのJSONArrayクラスで解析します。
逆順に読み取るポイントはとてもシンプルです。forループのカウンタ変数をi = array.length() - 1から始め、i--で0に達するまで減らしながら処理することで、配列の要素を後ろから順番に取り出すことができます。
ステップ1:新規プロジェクトを作成する
Android Studioを起動し、メニューから「File → New Project」を選択します。必要事項を入力して新しいプロジェクトを作成してください。
ステップ2:レイアウトファイルの作成(res/layout/activity_main.xml)
以下のコードをres/layout/activity_main.xmlに記述します。取得したデータを画面に表示するためのTextViewを1つ配置しています。
<?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>
上記のレイアウトでは、JSONオブジェクトから取得したユーザー名(name)を表示するためのTextViewを定義しています。
ステップ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;
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);
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
textView.setText(response.toString());
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");
UserInfo userInfo = new UserInfo(name);
textView.setText(userInfo.name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("error", error.toString());
}
});
queue.add(request);
}
private class UserInfo {
String name;
public UserInfo(String name) {
this.name = name;
}
}
}
このコードでは、VolleyのStringRequestを使って指定したURLから文字列レスポンスを非同期で取得し、onResponse()内でJSONObjectに変換しています。続いてgetJSONArray("users")でJSON配列を取り出し、for文を「配列の長さ - 1」から「0」まで逆向きに回すことで、各要素のnameフィールドを末尾から順に読み取っています。
ステップ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" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ステップ5:build.gradleに依存関係を追加する
以下のコードをbuild.gradle(モジュール: app)に記述し、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端末をPCに接続し、Android Studioでプロジェクトのアクティビティファイルを開いた状態で、ツールバーの「Run」アイコンをクリックします。実行デバイスとして自分のスマートフォンを選択すると、端末の画面に実行結果が表示されます。

-
Androidアプリでテキストファイルを簡単に読み込む方法【サンプルコード付き】
この記事では、Androidアプリでシンプルなテキストファイルを読み込む方法を、実際のサンプルコードとともにステップごとに解説します。res/rawフォルダに配置したテキストファイルを読み込み、画面に表示するまでの一連の流れを学ぶことができます。 ステップ1:プロジェクトの作成とテキストファイルの配置 まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。 続いて、新しいAndroidリソースディレクトリとして「raw」フォルダを作成し、読み込みたいテキストファ
-
AndroidでJSON配列を反復処理する方法をステップごとに解説
この記事では、Androidアプリ開発においてJSON配列(JSONArray)を反復処理する方法を、実際のサンプルコードとともにステップ形式で解説します。org.jsonパッケージのJSONObjectとJSONArrayクラスを使用して、JSON文字列からデータを取り出し、画面に表示するまでの一連の流れを学べます。完成イメージ本チュートリアルでは、従業員情報(ID・名前・給与)を含むJSON文字列を解析し、各要素を順番に読み取ってTextViewに表示するシンプルなアプリを作成します。手順1:Android Studioで新規プロジェクトを作成するまず、Android Studioを起動し