본문 바로가기

Android

네이버 API를 이용한 도서검색,더보기

holder.txtprice.setText(array.get(position).getPrice() + "");

Integer 타입은 text로 넘겨주면 오류가 납니다.. 꼭 ""을 붙이십시오.

 

NaverAPI.java

package com.example.ex16;
import java.net.*;
import  java.io.*;
public class NaverAPI {
    //결과 값을 받기 위해서 return
    public static String main(String apiURL,String query,int start) {
        //static: 클래스 생성없이 메서드 사용가능
        String clientId = "r_XLF45OBi3Xw08BTmvq";//애플리케이션 클라이언트 아이디값";
        String clientSecret = "DjUKEbgt13";//애플리케이션 클라이언트 시크릿값";
        try {
            String text = URLEncoder.encode(query, "UTF-8");
            apiURL += "query="+ text; // json 결과
            //String apiURL = "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml 결과
            apiURL += "&start=" + start;
            apiURL += "&display=10";

            URL url = new URL(apiURL);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("X-Naver-Client-Id", clientId);
            con.setRequestProperty("X-Naver-Client-Secret", clientSecret);
            int responseCode = con.getResponseCode();
            BufferedReader br;
            if(responseCode==200) { // 정상 호출
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            } else {  // 에러 발생
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
            System.out.println(response.toString());
            return response.toString();
        } catch (Exception e) {
            System.out.println(e);
            return e.toString();
        }
    }
}

BookVO.java

package com.example.ex16;

public class BookVO extends BlogVO{
   private String author;
   private int price;
   private String image;

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }


    @Override
    public String toString() {
        return "BookVO{" +
                "author='" + author + '\'' +
                ", price=" + price +
                ", image='" + image + '\'' +
                '}';
    }
}

BookAdapter.java

package com.example.ex16;

import android.content.Context;

import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

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


import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class BookAdapter extends RecyclerView.Adapter<BookAdapter.ViewHolder> {
    ArrayList<BookVO> array;
    Context context;


    public BookAdapter(ArrayList<BookVO> array, Context context) {
        this.array = array;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book,null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String image=array.get(position).getImage();
        int price=array.get(position).getPrice();

        holder.txtprice.setText(array.get(position).getPrice() + "원");
        holder.txttitle.setText(Html.fromHtml(array.get(position).getTitle()));

        Picasso.with(context).load(image).into(holder.image);
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView image;
        TextView txttitle, txtprice;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            txttitle=itemView.findViewById(R.id.txttitle);
            txtprice=itemView.findViewById(R.id.txtprice);
            image=itemView.findViewById(R.id.image);
        }
    }
}

BookActivity.java

package com.example.ex16;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;


import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class BookActivity extends AppCompatActivity {
    //데이터를 생성하기 위해서
    ArrayList<BookVO> array;
    String apiURL="https://openapi.naver.com/v1/search/book.json?";
    String query="안드로이드";
    int start=1;

    RecyclerView list;
    BookAdapter adapter;


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


        getSupportActionBar().setTitle("도서검색");

        list=findViewById(R.id.list);
        LinearLayoutManager manager=new LinearLayoutManager(this);
        list.setLayoutManager(manager);

        //생성
        array=new ArrayList<BookVO>();

        //생성
        new BookThread().execute();



        final EditText edtsearch=findViewById(R.id.edtsearch);
        edtsearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                start = 1;
                array.clear();
                query = edtsearch.getText().toString();
                new BookThread().execute();
                return false;
            }
        });
        FloatingActionButton btnmore=findViewById(R.id.btnmore);
        btnmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start += 10;
                new BookThread().execute();
            }
        });
    }
    //BackThread 생성
    class BookThread extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... strings) {
            return NaverAPI.main(apiURL,query,start);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            System.out.println("결과.........."+s);
            try {
                JSONArray jArray=new JSONObject(s).getJSONArray("items");
                for(int i=0; i<jArray.length(); i++){
                    JSONObject obj=jArray.getJSONObject(i);
                    BookVO vo=new BookVO();
                    vo.setAuthor(obj.getString("author"));
                    vo.setImage(obj.getString("image"));
                    vo.setPrice(obj.getInt("price"));
                    vo.setDescription(obj.getString("description"));
                    vo.setLink(obj.getString("link"));
                    vo.setTitle(obj.getString("title"));
                    array.add(vo);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            adapter=new BookAdapter(array,BookActivity.this);
            list.setAdapter(adapter);
            list.scrollToPosition(start);
        }
    }
}

item_book.xml

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10sp"
    android:background="#4B03A9F4">
    <ImageView
        android:id="@+id/image"
        android:layout_width="70sp"
        android:layout_height="50sp"
        android:src="@drawable/ic_launcher_background"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txttitle"
        android:layout_toRightOf="@id/image"
        android:text="책제목"
        android:textSize="20sp"
        android:singleLine="true"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtprice"
        android:text="책가격"
        android:textSize="15sp"
        android:layout_toRightOf="@id/image"
        android:layout_below="@id/txttitle"
        android:layout_centerVertical="true"/>
</RelativeLayout>