Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 JSON 배열을 역순으로 읽는 방법

개요

이 튜토리얼에서는 안드로이드에서 JSON 배열을 역순으로 읽어 화면에 표시하는 방법을 단계별로 살펴봅니다. 서버에서 데이터를 받아오기 위해 Volley 라이브러리를 사용하고, org.json 패키지의 JSONArray를 이용해 배열의 마지막 요소부터 첫 번째 요소까지 순회하는 방식을 구현합니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project를 선택한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.

2단계 — 레이아웃 파일 수정

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>

위 코드에서는 JSON 객체에서 NAME 값을 화면에 출력하기 위해 TextView를 사용했습니다.

3단계 — MainActivity 작성

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;
}
}
}

역순 처리의 핵심은 for 루프입니다. 인덱스를 배열 길이에서 1을 뺀 값부터 시작해 0까지 감소시키며 getJSONObject(i)로 각 항목을 가져오면, 마지막 요소부터 첫 번째 요소까지 차례대로 읽을 수 있습니다. 여기서는 각 사용자의 name 값을 추출해 TextView에 표시합니다.

4단계 — 매니페스트 설정

AndroidManifest.xml에 다음 코드를 추가합니다. 네트워크 통신을 위해 인터넷 권한 선언이 반드시 필요합니다.

<?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단계 — 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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 결과가 표시됩니다.

안드로이드에서 JSON 배열을 역순으로 읽는 방법