본문 바로가기

Android

네이버 API 뉴스 검색

 

버튼을 누르면 추가됩니다.

    activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:layout_margin="10sp">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btnmore"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        app:srcCompat="@drawable/ic_more"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_margin="10sp"/>
</RelativeLayout>


item.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="wrap_content"
    android:padding="10sp"
    android:background="#FF9800"
    android:orientation="vertical"
    android:layout_margin="50sp">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:text="여기에는 제목 출력"
        android:textColor="#ffffff"
        android:textSize="20sp"
        android:id="@+id/txttitle"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:text="여기에는 내용 출력"
        android:textColor="#FFEB3B"
        android:textSize="15sp"
        android:id="@+id/txtcontent"/>
</LinearLayout>


NaverAPI.java

package com.example.ex14;


import java.net.*;
import java.io.*;
public class NaverAPI {
    public static String search(String query,int start) {
        String clientId = "r_XLF45OBi3Xw08BTmvq";//애플리케이션 클라이언트 아이디값";
        String clientSecret = "DjUKEbgt13";//애플리케이션 클라이언트 시크릿값";

        try {
            String text = URLEncoder.encode(query, "UTF-8");
            String apiURL = "https://openapi.naver.com/v1/search/news.json?query="+ text; // json 결과
            //String apiURL = "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml 결과
            apiURL += "&start" +start;

            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("error..............." + e.toString());
            return e.toString();
        }
    }
}


NewsVO.java

package com.example.ex14;

public class NewsVO {
    private String title;
    private String content;
    private  String link;




    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }
}


NewsAdapter.java

package com.example.ex14;

import android.content.Context;
import android.text.Html;
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 NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
    ArrayList<NewsVO> array;
    Context context;

    public NewsAdapter(ArrayList<NewsVO> 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.ittem,null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.txttitle.setText(Html.fromHtml(array.get(position).getTitle()));
        holder.txtcontent.setText(Html.fromHtml(array.get(position).getContent()));
    }

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

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


MainActivity.java

package com.example.ex14;

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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SearchView;

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

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

import java.lang.reflect.Array;
import java.util.ArrayList;

//MainActivity는 메인 THRED
public class MainActivity extends AppCompatActivity {
    ArrayList<NewsVO> array;
    RecyclerView list;
    NewsAdapter adapter;
    //초기값 설정
    String query="수능";
    int start=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //NaverAPI에 search메서드가 static으로 정의되어있어 클래스를 생성하지않고 사용


        getSupportActionBar().setTitle("뉴스검색");



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

        array=new ArrayList<NewsVO>();
        //클래스 생성
        new NaverThread().execute();

        FloatingActionButton btnmore=findViewById(R.id.btnmore);
        btnmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start += 10;
                new NaverThread().execute();
            }
        });
    }
    //naver접속 위한 thread 정의
    //BACK THREAD
    class NaverThread extends AsyncTask<String, String, String>{
        @Override
        protected String doInBackground(String... strings) {
            //System.out.println(".....................................");
            return NaverAPI.search(query,start);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        //결과출력
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            System.out.println(s);


            try {

                //total값 가져오기
                int total=new JSONObject(s).getInt("total");
                System.out.println("total" + total);

                JSONArray jArray=new JSONObject(s).getJSONArray("items");
                for(int i=0; i<jArray.length(); i++){
                    JSONObject obj=jArray.getJSONObject(i);
                    NewsVO vo=new NewsVO();
                    vo.setTitle(obj.getString("title"));
                    vo.setContent(obj.getString("description"));
                    vo.setLink(obj.getString("link"));
                    array.add(vo);
                    System.out.println("결과............." + vo.getTitle());

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            adapter=new NewsAdapter(array,MainActivity.this);
            list.setAdapter(adapter);
            list.scrollToPosition(start);



        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        MenuItem search=menu.findItem(R.id.search);
        SearchView searchView=(SearchView)search.getActionView();

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                query=query;
                start=1;
                array.clear();
                new NaverThread().execute();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                query=newText;
                start=1;
                array.clear();
                new NaverThread().execute();
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }
}


menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/search"
        android:title="검색"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="android.widget.SearchView"/>
</menu>