땀이 삐질삐질 나는 개발 일기

RecyclerView 와 Retrofit2를 사용해 영화 목록 얻어오기 본문

개발 Tip

RecyclerView 와 Retrofit2를 사용해 영화 목록 얻어오기

삐질 2019. 4. 11. 21:41

개요

영화진흥위원회 오픈 API를 이용해 리사이클러뷰 Item ADD

Base Url:http://www.kobis.or.kr/

Path : kobisopenapi/webservice/rest/movie/searchMovieList.xml?key

Query : key = 430156241533f1d058c603178cc3ca0e(테스트 키)

Lib :Recyclerview , Retrofit2

*Reference URL : *http://www.kobis.or.kr/kobisopenapi/homepg/apiservice/searchServiceInfo.do

사용

안드로이드 X 기준으로 gradle 세팅되었습니다.

*기존 support 라이브러리를 이용하실 분은 *

https://developer.android.com/jetpack/androidx/migrate**해당 URL에서 대체되는 라이브러리를 추가하시면 됩니다.**

Gradle Dependency

//recyclerview  
implementation 'androidx.recyclerview:recyclerview:1.0.0'  

//retrofit2  
implementation 'com.squareup.retrofit2:retrofit:2.5.0'  
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'  

main_activity.xml

<LinearLayout xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"  
xmlns:tools="[http://schemas.android.com/tools](http://schemas.android.com/tools)"  
android:layout\_width="match\_parent"  
android:layout\_height="match\_parent"  
tools:context=".test.recyclerview.MainActivity">

<androidx.recyclerview.widget.RecyclerView  
android:id="@+id/recyclerview"  
android:layout\_width="match\_parent"  
android:layout\_height="match\_parent" />

item_movie.xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android\="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"  
android:layout\_width="match\_parent"  
android:layout\_height="wrap\_content"  
android:orientation="vertical"\>  
<TextView  
android:id="@+id/txtTitle"  
android:layout\_width="match\_parent"  
android:layout\_height="wrap\_content"  
android:text="123123123"  
android:textColor="#000000" />  
</LinearLayout>

*자바 코드 *

MainActivity.java

public class MainActivity extends AppCompatActivity {  

private RecyclerView recyclerView;  
private Adapter adapter;  

@Override  
protected void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
setContentView(R.layout.activity\_main);  
init();  
}  

public void init() {  
adapter \= new Adapter(this,R.layout.item\_movie);  
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);  
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);  
recyclerView \= findViewById(R.id.recyclerview);  
recyclerView.setLayoutManager(linearLayoutManager);  

recyclerView.setAdapter(adapter);  
getMovieList();  
}  

public void getMovieList(){  

Call<ResponseBody> call =NetworkHelper.getInstance().getApiService().getMovieList(Const.KEY);  
call.enqueue(new Callback<ResponseBody>() {  
@Override  
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {  
if(response.code()==200){  
ResponseBody responseBody = response.body();  
try {  
JsonParser parser= new JsonParser();  
JsonObject jsonObject = parser.parse(responseBody.string())  
.getAsJsonObject().get("movieListResult").getAsJsonObject();  
JsonArray array = jsonObject.get("movieList").getAsJsonArray();  

List<String> items = new ArrayList<>();  
for(int i =0 ; i<array.size(); i++){  
JsonObject insideObject = array.get(i).getAsJsonObject();  
String movieNm =insideObject.get("movieNm").getAsString();  
items.add(movieNm);  
}  
adapter.addItem(items);  
adapter.notifyDataSetChanged();  
} catch (IOException e) {  
e.printStackTrace();  
}  

}  
else{  
Log.e("리스폰 코드",""+response.code());  
}  

}  

@Override  
public void onFailure(Call<ResponseBody> call, Throwable t) {  
Log.e("리스폰 코드",""+t.getMessage());  
}  
});  
}  
}

Adapter.java

public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {  

private Context context;  
private int layoutId;  

private List<String> items;  

public Adapter(Context context, int layoutId) {  
this.context \= context;  
this.layoutId \= layoutId;  

}  

@NonNull  
@Override  
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {  
View view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);  
return new ItemViewHolder(view);  
}  

@Override  
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {  
String item = items.get(position);  
if (holder instanceof ItemViewHolder) {  
((ItemViewHolder) holder).textView.setText(item);  
}  

}  

@Override  
public int getItemCount() {  
return items \== null ? 0 : items.size();  
}  

public void addItem(List<String> item) {  
if (items \== null)  
items \= new ArrayList<>();  
items.addAll(item);  
}  

public static class ItemViewHolder extends RecyclerView.ViewHolder {  
private TextView textView;  

public ItemViewHolder(@NonNull View itemView) {  
super(itemView);  
textView \= itemView.findViewById(R.id.txtTitle);  
}  
}  
}

apiService.interface

public interface ApiService {  

@GET("kobisopenapi/webservice/rest/movie/searchMovieList.json")  
Call<ResponseBody> getMovieList(@Query("key") String key);  
}

**Const.java**

public class Const {  
public static final String BASEURL \="[http://www.kobis.or.kr/](http://www.kobis.or.kr/)";  
public static final String KEY \="430156241533f1d058c603178cc3ca0e";  


}

NetwrokHelper.java

public class NetworkHelper {  
private Retrofit retrofit;  
private ApiService apiService;  
public static NetworkHelper networkHelper \= new NetworkHelper();  

public NetworkHelper() {  
retrofit \= new Retrofit.Builder()  
.baseUrl(Const.BASEURL)  
.addConverterFactory(GsonConverterFactory.create())  
.build();  

apiService \=retrofit.create(ApiService.class);  
}  

public static NetworkHelper getInstance() {  
return networkHelper;  
}  

public ApiService getApiService() {  
return apiService;  
}  
}
Comments