군침이 싹 도는 코딩

안드로이드 네트워크 통신을 위한 Volley 라이브러리 및 JSON 데이터 파싱 본문

Android

안드로이드 네트워크 통신을 위한 Volley 라이브러리 및 JSON 데이터 파싱

mugoori 2023. 2. 3. 12:30
dependencies {
    implementation 'com.android.volley:volley:1.2.1'
}

# Volley 라이브러리를 사용하기 위해 먼저 빌드 그리들에 해당 코드를 복사해준다

최선버전을 확인하려면 https://google.github.io/volley/ 여기로 가면 된다

 

 

package com.mugoori.networkapp1;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DownloadManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

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.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    TextView txtUserId;
    TextView txtId;
    TextView txtTitle;
    TextView txtBody;

    final String URL = "https://jsonplaceholder.typicode.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtUserId = findViewById(R.id.txtUserId);
        txtId = findViewById(R.id.txtId);
        txtTitle = findViewById(R.id.txtTitle);
        txtBody = findViewById(R.id.txtBody);

        // Volley 로 네트워크 통신한다
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL + "/posts/1", null, new Response.Listener<JSONObject>() {
            
                    @Override
                    public void onResponse(JSONObject response) {

                        Log.i("NETWORK_APP",response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }

        );
        // 이코드가 있어야, 네트워크 실행한다.
        queue.add(request);




    }
}

# 네트워크 통신을 위해 URL 을 상수로 만들어주고 화면의 뷰들을 연결한다 

Volley.newRequestQueue ( 현재 액티비티 ) 를 쓰고

제이슨 형식 1개를 가져오기때문에 JsonObjectRequest 를 써준다 

파라미터 ( http 메소드 방식 , 경로 , 보낼 데이터 , Response  )

해당 코드에서는 http 메소드가 GET 이므로 보낼 데이터가 없다