api를 이용하여 영화 정보 가져오기

2022. 6. 18. 22:43·안드로이드 with 자바/응용 문제들

0. 응용한 기술

- 이미지 또한 api를 가져와서 영화 이미지를 구현해본다.

( 여기서는 대충 아무 인터넷에 있는 자료를 가져와본다. )

 

 

 

 

1. 구현해야 할 것

 

 

 

 

 

2. 제약조건

- api 주소는 아래에 있는 사이트 주소로 이용한다.

 

http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20120101

 

 

 

 

3. java 소스코드

 

( 아래는 MainActivity.java의 코드이다. )

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringBufferInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    EditText ed1;
    Button btn1;

    RequestQueue requestQueue;

    RecyclerView recyclerView;
    MovieAdapter movieAdapter;

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

        ed1 = findViewById(R.id.editText);

        btn1 = findViewById(R.id.button);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = ed1.getText().toString();
                makeRequest(url);
            }
        });

        if(requestQueue == null){
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false);
        recyclerView.setLayoutManager(layoutManager);

        movieAdapter = new MovieAdapter();
        recyclerView.setAdapter(movieAdapter);
    }

    private void makeRequest(String url) {
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        processResponse(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        request.setShouldCache(false);
        requestQueue.add(request);
    }

    private void processResponse(String response) {
        Gson gson = new Gson();
        MovieList movieList = gson.fromJson(response, MovieList.class);
        int movieSize = movieList.boxOfficeResult.dailyBoxOfficeList.size();

        for(int i=0; i<movieSize; i++){
            Movie movie = movieList.boxOfficeResult.dailyBoxOfficeList.get(i);

            movieAdapter.addItem(movie);
        }

        movieAdapter.notifyDataSetChanged();
    }
}

 

 

( 아래는 MovieList, MovieListResult, Movie의 클래스이다. )

 

( api 주소마다 속성값이 틀리므로, 변수의 이름을 주의해야 한다. )

 

 

 

 

( 아래는 MovieAdapter.class 이다. )

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder>{
    ArrayList<Movie> items = new ArrayList<>();

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.movie_item, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Movie item = items.get(position);
        holder.setItem(item);
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public void addItem(Movie movie) {
        items.add(movie);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        TextView tv1, tv2;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tv1 = itemView.findViewById(R.id.textView);
            tv2 = itemView.findViewById(R.id.textView2);
        }

        public void setItem(Movie item){
            tv1.setText(item.movieNm);
            tv2.setText(item.audiCnt + "명");
        }
    }
}

 

 

 

 

4. xml 소스코드

 

( 아래는 activity_main.xml의 코드이다. )

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="text"
        />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="요청하기" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="10dp"/>

</LinearLayout>

 

 

 

 

( 아래는 movie_item.xml 이다. )

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="4dp"
        android:layout_marginBottom="4dp"
        app:cardBackgroundColor="#FFFFFFFF"
        app:cardCornerRadius="10dp"
        app:cardElevation="5dp" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:padding="5dp"
                app:srcCompat="@drawable/movie" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="5dp"
                android:layout_weight="1"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/textView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:maxLines="1"
                    android:text="제목"
                    android:textSize="22sp" />

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:gravity="right"
                    android:paddingRight="10dp"
                    android:text="관객수"
                    android:textColor="#FF0000FF"
                    android:textSize="16sp" />
            </LinearLayout>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

 

 

 

 

5. 아래는 메니페스트와 gradle에 추가해야하는 코드

 

 

 

 

6. 추가로 구현해볼 것.

- Glide와 Picasso의 라이브러리를 이용하여 각 영화에 맞는 이미지 구현해보기.

 

 

( 아래는 Gilde로 구현하여 위의 코드를 수정한 코드입니다. )

 

( MainActivity.class )

( 이때 url은 Movie 클래스에서 추가한 인스턴스 멤버 변수이며, 해당하는 영화의 이미지에 맞게

구현하면 된다. )

 

 

( MovieAdapter.class의 ViewHolder )

 

 

( MovieAdapter.class의 onBindViewHolder() )

 

 

 

저작자표시 (새창열림)

'안드로이드 with 자바 > 응용 문제들' 카테고리의 다른 글

애니메이션을 이용한 카드뷰 만들어보기(1)  (0) 2022.07.26
리싸이클러뷰를 이용하여 정보 추가, 삭제하기 (2)  (0) 2022.07.26
리싸이클러뷰를 이용하여 정보 추가, 삭제하기 (1)  (0) 2022.07.21
프로그래스바를 이용하여 진행도 알려주기  (0) 2022.05.18
'안드로이드 with 자바/응용 문제들' 카테고리의 다른 글
  • 애니메이션을 이용한 카드뷰 만들어보기(1)
  • 리싸이클러뷰를 이용하여 정보 추가, 삭제하기 (2)
  • 리싸이클러뷰를 이용하여 정보 추가, 삭제하기 (1)
  • 프로그래스바를 이용하여 진행도 알려주기
백_곰
백_곰
  • 백_곰
    친절한 코딩
    백_곰
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 알고리즘 (with JAVA)
        • 기본 알고리즘
        • 완전 탐색
        • 분할 정복 알고리즘
        • 동적 계획법
        • 탐욕법
        • 코딩 테스트 기출 문제
        • 코드트리 조별과제
      • 백준 (with JAVA)
        • 완전 탐색
        • 분할 정복
        • 그 외
      • 자바
        • 개발 환경 구축하기
        • 팁
        • 기본적인 개념
        • 컬렉션 프레임워크
        • 프로세스와 쓰레드
        • 지네릭스
        • 람다식
        • 스트림
        • 입출력 IO
        • 네트워킹
        • 열거형(enums)
        • java.lang 패키지
        • java.time 패키지
        • 유용한 클래스들
        • 형식화 클래스들
      • 안드로이드 with 자바
        • 응용 문제들
        • 자잘한 문제들
        • 오류 보고서
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      소켓 프로그래밍
      문자 기반 스트림
      역직렬화
      TCP 소켓 프로그래밍
      serializable
      ServerSocket
      알고스팟
      InputStream
      java.time 패키지
      제자리 정렬
      java.lang패키지
      map()
      선택 정렬
      유용한 클래스
      안드로이드 스튜디오
      코딩테스트
      Arrays
      중간연산
      람다식
      outputstream
      자바 개념
      코딩트리조별과제
      코드트리
      불안정 정렬
      snail
      file
      스트림
      다형성
      Collections Framework
      안정 정렬
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.3
    백_곰
    api를 이용하여 영화 정보 가져오기
    상단으로

    티스토리툴바