자라나라 개발머리

3. 스프링 부트 - 안드로이드 스튜디오 연결/Retrofit2 (완) 본문

프로젝트/개인

3. 스프링 부트 - 안드로이드 스튜디오 연결/Retrofit2 (완)

iammindy 2023. 2. 25. 18:48

2편 작성이 벌써 한 달이나 지났다. 기간 내에 완성은 했지만 캡스톤 개발 시작+다른 일로 포스팅을 열심히 미루다,, 더 이상 미룰 수 없다! 싶어서 작성한다.

 

저번에 스프링부트와 MySQL을 연결하고 테스트까지 해보았다.

오늘은 스프링부트로 작성한 REST API와 안드로이드 스튜디오를 Retrofit2를 이용해서 연결하고, 어플에서 전체회원을 조회해본다.

 

참고:

https://velog.io/@re-deok/Android-Retrofit2%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%B4%EC%84%9C-Android-Studio%EC%97%90-RESTful-API-%EC%97%B0%EB%8F%99

 

[Android] Retrofit2를 이용해서 Android Studio에 REST API 연동

안드로이드 스튜디오랑 스프링 부트로 만든 REST API 통신하기~~

velog.io

 

위 링크와 거의 일치하게 코드를 짰으니 자세한건 위 링크를 참고해주세요 :)

 

사전 세팅

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET" /> //추가
    
    
    <application>
			android:usesCleartextTraffic="true" //추가
            .
            .
            .
	</application>

.
.
.

</manifest>

 

build.gradle

dependencies {
	implementation 'com.squareup.retrofit2:retrofit:2.9.0' // retrofit2
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // Gson 변환기
}

 

코드

 

Member.java

package com.example.myapplication;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Member {

    @SerializedName("id")
    @Expose
    private String id;

    @SerializedName("name")
    @Expose
    private String name;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

 

Retrofit_interface.java

package com.example.myapplication;

import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.http.FieldMap;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;

public interface Retrofit_interface {

    @GET("Member/all")
    Call<List<Member>> getMembers();

}

 

retrofit_client.java

package com.example.myapplication;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class retrofit_client {
    private static final String BASE_URL = "https://jsonplaceholder.typicode.com/";


    public static Retrofit_interface getApiService(){return getInstance().create(Retrofit_interface.class);}

    private static Retrofit getInstance(){
        Gson gson = new GsonBuilder().setLenient().create();
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }

}

 

MainActivity.java

package com.example.myapplication;

import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.myapplication.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    Call<Member> call;
    private TextView textView;

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

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://10.0.2.2:8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Retrofit_interface retrofit_interface = retrofit.create(Retrofit_interface.class);
        Call<List<Member>> call = retrofit_interface.getMembers();
        call.enqueue(new Callback<List<Member>>() {
            @Override
            public void onResponse(Call<List<Member>> call, Response<List<Member>> response) {
                if (!response.isSuccessful()) {
                    textView.setText("Code: " + response.code());
                    return;
                }
                List<Member> members = response.body();
                for (Member member : members) {
                    String content = "";
                    content += "ID: " + member.getId() + "\n";
                    content += "Title: " + member.getName() + "\n\n";
                    textView.append(content);
                }
            }

            @Override
            public void onFailure(Call<List<Member>> call, Throwable t) {
                textView.setText(t.getMessage());
            }
        });
    }
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginBottom="30dp"
        android:orientation="vertical">


        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="회원목록\n"/>

    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

 

테스트

 

스프링 부트 실행후 포스트맨으로 아래와 같이 회원 생성.

(작성 시점에 깨달았지만 생성은 관례적으로 PUT맵핑이 아니고 POST맵핑을 쓰는거였다^^,,)

 

그리고 안드로이드 스튜디오 가상머신에서 실행시키면!

이렇게 DB에 저장된 회원 전체를 안드로이드 앱에서 조회 할 수 있다!

 

마무리

짧은 기간동안 아주 작은 토이 프로젝트를 혼자 해봤다.

물론 이 모든 지식이 내 머릿속에 있는건 아니지만, 본 개발에 앞서 흐름 잡는 것에 더 없이 도움 된 것 같다.

지금도 개발하면서 가끔씩 내가 작성했던 글을 보며 상기 시키기도 한다. 기록의 중요성을 체감한다.