개발관련일지

AND ] 안드로이드 레트로핏 사용하기 본문

개발기록/안드로이드

AND ] 안드로이드 레트로핏 사용하기

BEECHANGBOT 2020. 5. 27. 02:07

사용하기 전에 찾아서 정리한 게시글 

https://beeyoo0o0ncha.tistory.com/16

 

AND ] 레트로핏 사용하기전 찾아본것들

retrofit - 기계속에 없던 부품을 새로 장착하다 - 서버와 http통신을 통해 전달된 데이터를 앱에서 받아 관리 할 수 있게 하는 라이브러리 (httpUrlConnetion으로 서버와 비동기로 통신하는걸 해주고 필�

beeyoo0o0ncha.tistory.com

 

레트로핏 인터페이스 선언

public interface RetroBaseApiService {
    String Base_URL = "YourServer";
    @GET("/도메인 뒤의 디렉토리설정")
    Call<List<ResponseGet>> getMethod(@QueryMap HashMap<String, String> param);
    //GET메소드를 사용하는걸 예시로 하였고 해쉬맵에 들어가는 값이 결국엔 ?ex1 = hello & ex2 = world로
    // 값이 들어가게 된다. 엑티비티에서 해쉬맵을 선언해서 넣어서 전달하게된다.
//  Call<List<ResponseGet>> getMethod(@Query("category") String id);
// 	위의 주석이 쳐져있는 방식은 하나만 get으로 보낼떄 사용하는거다 차이는 
//	어노테이션이 커리이며 해쉬맵은 커리맵으로 차이가 있다.
}

 메인쓰레드에 들어가기 위해 사용될 콜백

public interface RetroCallback<T> {
    void onError(Throwable t);

    void onSuccess(int code, T receivedData);

    void onFailure(int code);
}

사용한 데이터 클래스 >> 서버로 부터 리스폰된 데이터를 담는 곳으로 사용한다.

내가 사용했던 예시로 올려놈


public class ResponseGet {

    private String infoUrl;
    private String infoCompany;
    private String infoName;
    private String infoImg;
    private String infoSecondCategory;
    public String infoColor;
    private String infoPrice;

    public String getInfoPrice() {
        return infoPrice;
    }

    public void setInfoPrice(String infoPrice) {
        this.infoPrice = infoPrice;
    }

    public ResponseGet(String infoUrl, String infoCompany, String infoName, String infoImg, String infoSecondCategory, String infoColor, String infoPrice) {
        this.infoUrl = infoUrl;
        this.infoCompany = infoCompany;
        this.infoName = infoName;
        this.infoImg = infoImg;
        this.infoSecondCategory = infoSecondCategory;
        this.infoColor = infoColor;
        this.infoPrice = infoPrice;

    }

    public String getInfoUrl() {
        return infoUrl;
    }

    public void setInfoUrl(String infoUrl) {
        this.infoUrl = infoUrl;
    }

    public String getInfoCompany() {
        return infoCompany;
    }

    public void setInfoCompany(String infoCompany) {
        this.infoCompany = infoCompany;
    }

    public String getInfoName() {
        return infoName;
    }

    public void setInfoName(String infoName) {
        this.infoName = infoName;
    }

    public String getInfoImg() {
        return infoImg;
    }

    public void setInfoImg(String infoImg) {
        this.infoImg = infoImg;
    }

    public String getInfoSecondCategory() {
        return infoSecondCategory;
    }

    public void setInfoSecondCategory(String infoSecondCategory) {
        this.infoSecondCategory = infoSecondCategory;
    }

    public String getInfoColor() {
        return infoColor;
    }

    public void setInfoColor(String infoColor) {
        this.infoColor = infoColor;
    }


}

 

레트로핏이 정리된 싱글톤방식 클래스

public class RetroClient {
    private RetroBaseApiService apiService;
    public static String baseUrl = RetroBaseApiService.Base_URL;
    private static Context context;
    private static Retrofit retrofit;

    private static class SingletonHolder {
        private static RetroClient INSTANCE = new RetroClient(context);
    }

    public static RetroClient getInstance(Context context) {
        if (context != null) {
            context = context;
        }
        return SingletonHolder.INSTANCE;
    }

    private RetroClient(Context context) {
        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
    }

    public RetroClient createBaseApi() {
        apiService = create(RetroBaseApiService.class);
        return this;
    }


    /**
     * create you ApiService
     * Create an implementation of the API endpoints defined by the {@code service} interface.
     */
    public <T> T create(final Class<T> service) {
        if (service == null) {
            throw new RuntimeException("Api service is null!");
        }
        return retrofit.create(service);
    }


    public void getMethod(HashMap input, final RetroCallback callback) {
        apiService.getMethod(input).enqueue(new Callback<List<ResponseGet>>() {
            @Override
            public void onResponse(Call<List<ResponseGet>> call, Response<List<ResponseGet>> response) {
                if (response.isSuccessful()) {
                    Log.e("getMethod" , String.valueOf(response));
                    callback.onSuccess(response.code(), response.body());

                } else {
                    callback.onFailure(response.code());
                }
            }

            @Override
            public void onFailure(Call<List<ResponseGet>> call, Throwable t) {
                callback.onError(t);
            }
        });
    }
}

 

 

호출하는 곳의 엑티비티



import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;

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

public class MainActivity extends AppCompatActivity {
    private static final String LOG = MainActivity.class.getSimpleName();
    private RetroClient retroClient;


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

        retroClient = RetroClient.getInstance(this).createBaseApi();
        retroGetMethod();
    }



    private void setError(String errorString) {
        Log.e(LOG, errorString);

    }

    private void setFailure(int code) {

    }

    public void retroGetMethod() {

        HashMap<String, String> input = new HashMap<>();
        input.put("key", "value");
        //해쉬맵을 추가한수 만큼 get메소드의 파라미터가 url에 포함전달된다.
        retroClient.getMethod(input, new RetroCallback() {
            @Override
            public void onError(Throwable t) {
                Log.e("onError", String.valueOf(t));
                setError(t.toString());
            }

            @Override
            public void onSuccess(int code, Object receivedData) {
                Log.e("code" , String.valueOf(code));
                List<ResponseGet> data = (List<ResponseGet>) receivedData;
                for (int i = 0; i < data.size(); i++) {
                    Log.e("data" + i, data.get(i).GETTER + "");
                    //TODO 데이터 클래스에서 데이터에 맞게 게터로 불러내면됨
                    
                }



            }

            @Override
            public void onFailure(int code) {
                setFailure(code);
                Log.e("onFailure", String.valueOf(code));
            }
        });
    }
}

클라단에서는 이렇게 하면 받을 준비가 되어있다. 중요한건 

.addConverterFactory(GsonConverterFactory.create())

을 사용했으므로 제이슨 형식으로 데이터가 리스폰 되어야한다. 

http://jsonplaceholder.typicode.com/posts

위의 사이트 처럼 제이슨 형식이면 되고 값은 DTO에서 서버에서 주는 값에 맞춰서 사용하면 된다. 

 

 

 

참고한 블로그 

https://kor45cw.tistory.com/5

https://altongmon.tistory.com/745

문제시 삭제하겠습니다.