본문 바로가기
안드로이드/개발자 일상

안드로이드 Retrofit2+RecyclerView 1-1(영화진흥위원회 오픈 API 이용)

by 차누감 2020. 3. 22.

이번 글에서는 안드로이드 Retrofit의 사용 방법에 대해 간략히 알아보겠습니다.

자세한 사항은 아래 Retrofit에 대한 사용 설명 사이트를 참고 바랍니다.

https://square.github.io/retrofit/

 

Retrofit

A type-safe HTTP client for Android and Java

square.github.io

그리고 화면에 보여줄 JSON데이터는 아래 사이트에서 가져왔습니다. (영화진흥위원회 오픈API)

간단히 회원 가입하면 API key를 쉽게 발급 받을 수 있습니다. (로그인 후, 키 발급  메뉴)

https://www.kobis.or.kr/kobisopenapi/homepg/apiservice/searchServiceInfo.do


<실행 화면> Retrofit을 이용하여 Json 데이터를 RecyclerView로 보여주었습니다.


우선 Retrofit2와 RecyclerView 라이브러리를 추가합니다.

Gradle:

implementation 'com.android.support:recyclerview-v7:28.0.0' //recyclerview

implementation 'com.squareup.retrofit2:retrofit:2.7.2' //retrofit2
implementation 'com.squareup.retrofit2:converter-gson:2.7.2'
//JSON을 변환해주는 Gson라이브러리로 retrofit2와 같이 사용합니다.

android:

compileOptions {
         sourceCompatibility JavaVersion.VERSION_1_8
         targetCompatibility JavaVersion.VERSION_1_8
}

서버 통신을 할 것이기 때문에 AndroidManifest.xml에

인터넷 접근 허용과 안드로이드 9.0 파이 버전 이상에서는 https를 사용하도록 했기 때문에 (예제에서는 http 사용)

http도 사용 할 수 있게 한 줄 코드를 추가합니다.

 

<uses-permission android:name="android.permission.INTERNET"/>

<application

android:usesCleartextTraffic="true"

activity_main.xml로 가서 기본 화면을 디자인 해줍니다.

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="utf-8"?>
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
        android:id="@+id/rv_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        android:orientation="vertical"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="RecyclerView show"
        android:onClick="click_btn"
        app:layout_constraintBottom_toBottomOf="parent"
        tools:layout_editor_absoluteX="111dp" />
 
 
 

처음 화면

그리고 데이터를 표현할 xml을 작성합니다.

(json에 정보가 많지만 "rank", "movieNm", "openDt" 3가지만 보여줄 겁니다.

저 이름은 Json file을 보고 작성한 것입니다.)

recyclerview_item.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?xml version="1.0" encoding="utf-8"?>
    android:layout_width="match_parent"
    android:layout_height="100dp"
    xmlns:tools="http://schemas.android.com/tools">
    <TextView
        android:id="@+id/tv_rank"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@color/colorAccent"
        android:textSize="24sp"
        android:textColor="#FFFFFF"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.12"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.506"/>
    <TextView
        android:id="@+id/tv_movieNm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.352"
        app:layout_constraintStart_toEndOf="@+id/tv_rank"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.506"
        tools:text="movieName" />
 
    <TextView
        android:id="@+id/tv_openDt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="16dp"
        android:textSize="14sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        tools:text="2020-01-01" />
 
 

각 아이템(데이터)의 모양

이제 어댑터를 만들겠습니다.

MyAdapter.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.example.ex_retrofit_recyclerview;
 
 
import androidx.annotation.NonNull;
 
 
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
 
    private ArrayList<Map<String, Object>> items= new ArrayList<Map<String, Object>>();
 
    public MyAdapter(ArrayList<Map<String, Object>> resultList){
        this.items=resultList;
    }
 
    @NonNull
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(itemView);
    }
 
 
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Map<String, Object> item = items.get(position);
        holder.setItem(item);
    }
 
    @Override
    public int getItemCount() {
        return items.size();
    }
 
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView tvRank, tvMovieNm, tvOpenDt;
        public MyViewHolder(View itemView) {
            super(itemView);
            tvRank=itemView.findViewById(R.id.tv_rank);
            tvMovieNm=itemView.findViewById(R.id.tv_movieNm);
            tvOpenDt=itemView.findViewById(R.id.tv_openDt);
 
        }
        public void setItem(Map<String, Object> item){
 
            //"rank", "movieNm", "openDt"은 Json파일에 저장되어 있던 key값
            tvRank.setText(item.get("rank").toString());
            tvMovieNm.setText(item.get("movieNm").toString());
            tvOpenDt.setText(item.get("openDt").toString());
 
        }
    }
}
 
 
 

이제 Retrofit을 이용하기 위해  Interface를 만들어 줍니다.

RetrofitInterface.java

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.example.ex_retrofit_recyclerview;
 
 
 
public interface RetrofitInterface {
    @GET("/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json")
    Call<Map<String,Object>> getBoxOffice(@Query("key"String key,
                                          @Query("targetDt"String targetDt);
}
 
 

 

이제 MainActivity.java를 작성합니다.

Retrofit으로 영화진흥위원회에서 데이터를 받아옵니다. 그리고 그 데이터를 알맞게 저장합니다.

버튼을 누렀을 시 recyclerview에 setAdapter해줍니다.

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.example.ex_retrofit_recyclerview;
 
 
 
 
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
 
public class MainActivity extends AppCompatActivity {
 
    private RecyclerView recyclerView;
    private RecyclerView.Adapter mAdapter;
 
    String baseUrl = "http://www.kobis.or.kr";
    String API_KEY = "영화진흥위원회에서 발급 받은 Key를 넣어주세요";
    Retrofit retrofit;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        recyclerView=findViewById(R.id.rv_recyclerview);
 
        //Retrofit 객체생성
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RetrofitInterface retrofitInterface= retrofit.create(RetrofitInterface.class);
 
        retrofitInterface.getBoxOffice(API_KEY,"20200319").enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
 
                Map<String,Object> boxOfficeResult= (Map<String, Object>response.body().get("boxOfficeResult");
                ArrayList<Map<String, Object>> jsonList = (ArrayList) boxOfficeResult.get("dailyBoxOfficeList");
                mAdapter=new MyAdapter(jsonList);
 
            }
 
            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
 
            }
        });
 
    }// onCreate()..
 
    public void click_btn(View view) {
        recyclerView.setAdapter(mAdapter);
    }
 
}// MainActivity class..
 
 

<실행 화면> Retrofit을 이용하여 Json 데이터를 RecyclerView로 보여주었습니다.

 

 

<심화 예제>

혹시 해당 리스트를 삭제하고 싶은데 평범하게 클릭해서 말고

드래그하여 선택하여 하는 예제

( 위 예제에서 삭제하는 기능만 추가하였습니다. )

2020/04/06 - [안드로이드/개발자 일상] - 안드로이드 Retrofit2+RecyclerView 1-2 (추가 밀어서 삭제,편집 )

댓글