안드로이드

 

                

 

class MainActivity

package kr.co.braverokmc.rss;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class MainActivity extends AppCompatActivity {
    private static final String TAG="MainActivity";

    EditText editText;
    TextView textView;
    ListView listView;
    RssAdapter rssAdapter;

    ArrayList<RssItem> arrayList;
    //노컷 뉴스
    //http://rss.nocutnews.co.kr/NocutEtc.xml

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

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


        editText=(EditText)findViewById(R.id.editText);
        textView=(TextView)findViewById(R.id.textView);
        listView=(ListView)findViewById(R.id.line1);

        RequestThread thread=new RequestThread();
        thread.setDaemon(true);
        thread.start();
    }


    public void onClick(View v){

        if(arrayList!=null){
            Log.i(TAG, arrayList.toString()+"\n\n\n\n\n\n");
            println(arrayList.toString()+"\n\n\n\n\n\n");

            handler.post(new Runnable() {
                @Override
                public void run() {

                    rssAdapter =new RssAdapter(MainActivity.this, R.layout.rss_item, arrayList);
                    listView.setAdapter(rssAdapter);
                }
            });

        }else{

            Toast.makeText(getApplicationContext(), "파싱 실패 " ,Toast.LENGTH_SHORT).show();
        }

    }


    class RequestThread extends Thread{
        @Override
        public void run() {

            try{
                String urlStr =editText.getText().toString();
                StringBuilder outputBuilder =new StringBuilder();


                URL url =new URL(urlStr);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //기본 속성 설정
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setConnectTimeout(15000); //접속시간 15초 여유

                int resCode =connection.getResponseCode();
                if(resCode==HttpURLConnection.HTTP_OK){
                    println("응답코드  :" +resCode);
                    InputStream inputStream =connection.getInputStream();

                    parseRSS(inputStream);
                   // println(outputBuilder.toString());
                }

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


    private void parseRSS(InputStream inputStream ){
        DocumentBuilder builder;
        try {
            //xml 파싱 Factory 생성
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // xml 파싱 객체 생성
            builder = factory.newDocumentBuilder();

            //  InputStream 으로 파싱 된것을 Document 로 받음
            Document document =builder.parse(inputStream);

            // xml 파싱을 for문으로 돌려 원하는  데이터를 추출 하여 객체에 저장
            ArrayList<RssItem>   itemList= paserDocument(document);

            println("파싱된 아이템 개수 :" +itemList.size());

            paserDocument(document);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private ArrayList<RssItem> paserDocument(Document document){

        // xml 파싱 전체 요소를 가져옴
        Element element =document.getDocumentElement();
        // Rss 에서 item 에 해당하는 것만을  NodeList  저장
        NodeList nodeList =element.getElementsByTagName("item");

        arrayList =new ArrayList<>();
        if(nodeList!=null){

            println(" nodeList getLength :" + nodeList.getLength());

            for(int i=0; i<nodeList.getLength(); i++){
                // node 가 item 에 해당하는 것만 반복문으로 돌린다.
                RssItem rssItem= pareItemNode(nodeList, i);
                arrayList.add(rssItem);
            }
        }
        return arrayList;
    }

    private RssItem pareItemNode(NodeList nodeList, int index){

        Element element =(Element)nodeList.item(index);

        // item 의 index 가 0, 1, 2, 3, 4, 5  nodeList 개수만큼 증가하면서
        // 원하는 데이터를 추출 한다.

        // item 중에 title 태그 요소를 추출한다.  title 이름이 하나 이기 때문에 첫번째 0번째
        // 동일한 title 이름이 여러개 있을 경우 반복문으로 돌린다.
        Element titleElement=(Element)element.getElementsByTagName("title").item(0);
        Element linkElement=(Element)element.getElementsByTagName("link").item(0);
        Element descriptionElement=(Element)element.getElementsByTagName("description").item(0);
        Element dcDateElement=(Element)element.getElementsByTagName("dc:date").item(0);
        Element authorElement=(Element)element.getElementsByTagName("author").item(0);




        String title="";
        if(titleElement!=null){
            //태그 안의 문자를 추출한다.
            Node firstChild=titleElement.getFirstChild();
            if(firstChild!=null){
                title=firstChild.getNodeValue();
               // println("title : " + title);
            }
        }


        String link="";
        if(linkElement!=null){
            //태그 안의 문자를 추출한다.
            Node firstChild=linkElement.getFirstChild();
            if(firstChild!=null){
                link=firstChild.getNodeValue();
                //println("link : " + link);
            }
        }

        String description="";
        if(descriptionElement!=null){
            //태그 안의 문자를 추출한다.
            Node firstChild=descriptionElement.getFirstChild();
            if(firstChild!=null){
                description=firstChild.getNodeValue();
                //println("description : " + description);
            }
        }



        String dcDate="00";
       if(dcDateElement!=null){
            //태그 안의 문자를 추출한다.
            Node firstChild=dcDateElement.getFirstChild();
            if(firstChild!=null){
                dcDate=firstChild.getNodeValue();
               // println("dcDate : " + dcDate);
            }
        }

        String author="";
        if(authorElement!=null){
            //태그 안의 문자를 추출한다.
            Node firstChild=authorElement.getFirstChild();
            if(firstChild!=null){
                author=firstChild.getNodeValue();
               // println("author : " + author);
            }
        }


        return new RssItem(title,link, description, dcDate, author);
    }



    private void println(final String data){

        handler.post(new Runnable() {
            @Override
            public void run() {
                textView.append(data +"\n");
            }
        });
    }





}

 

 

R.layout.activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="http://www.chosun.com/site/data/rss/ent.xml"
        android:ems="10"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/editText"

        />

    <Button
        android:text="RSS 요청하기"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText"
        android:id="@+id/button"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="onClick"
        />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="140dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/editText"
        android:background="@android:color/holo_orange_light"
        android:id="@+id/scrollView"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/textView"
            />
        
    </ScrollView>
    
    
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/line1"
        android:layout_below="@+id/scrollView">

    </ListView>


</RelativeLayout>

 

 

class RssAdapter

package kr.co.braverokmc.rss;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by choi on 2017-04-15.
 */

public class RssAdapter extends BaseAdapter {
    //http://braverokmc.dothome.co.kr/m02/android/view/291
    private static final String TAG="RssAdapter";

    Context mContext;
    int layout;
    List<RssItem> items;

    ImageView imageView;
    TextView  title, link, description, author, dcDate;

    public RssAdapter(Context context, int resource, List<RssItem> objects) {

        this.mContext=context;
        this.layout=resource;
        this.items=objects;
    }

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


    @Override
    public Object getItem(int position) {
        return items.get(position);
    }



    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        RssItemView view=null;

        if(convertView==null){
            view =new RssItemView(mContext);
        }else{
            view =(RssItemView)convertView;
        }

        view.setRssItem(items.get(position));

        return view;
    }


   /* @Override
    public View getView(int position, View convertView, ViewGroup parent) {

         LinearLayout view=null;

         if(convertView==null){

             LayoutInflater inflater =(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             convertView =inflater.inflate(layout, parent, false);


             imageView=(ImageView)convertView.findViewById(R.id.image1);
             title=(TextView)convertView.findViewById(R.id.title);
             link=(TextView)convertView.findViewById(R.id.link);
             description=(TextView)convertView.findViewById(R.id.description);
             author=(TextView)convertView.findViewById(R.id.author);
             dcDate=(TextView)convertView.findViewById(R.id.dcDate);


         }
           view = (LinearLayout) convertView;


            title.setText(items.get(position).getTitle());
            link.setText(items.get(position).getLink());
            description.setText(items.get(position).getDescription());
            author.setText(items.get(position).getAuthor());
            dcDate.setText(items.get(position).getDcDate());


     return view;
    }*/



}

 

R.layout.rss_item

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

    <ImageView
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:background="#ffeeccdd"
        android:layout_gravity="center_vertical|center_horizontal"
        android:id="@+id/image1"
        />
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="5dp"
        android:layout_gravity="center_vertical"
        >
        
        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/link"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/dcDate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/author"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />


    </LinearLayout>



</LinearLayout>

 

class RssItemView

package kr.co.braverokmc.rss;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by choi on 2017-04-16.
 */

public class RssItemView extends LinearLayout{

    ImageView imageView;
    TextView  title, link, description, author, dcDate;


    public RssItemView(Context context) {
        super(context);
        init(context);

    }

    public RssItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }


    public void init(Context context){

        LayoutInflater layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layoutInflater.inflate(R.layout.rss_item, this, true);

        imageView=(ImageView)findViewById(R.id.image1);
        title=(TextView)findViewById(R.id.title);
        link=(TextView)findViewById(R.id.link);
        description=(TextView)findViewById(R.id.description);
        author=(TextView)findViewById(R.id.author);
        dcDate=(TextView)findViewById(R.id.dcDate);

    }


    public void setRssItem(RssItem item){
        title.setText(item.getTitle());
        link.setText(item.getLink());
        description.setText(item.getDescription());
        author.setText(item.getAuthor());
        dcDate.setText(item.getDcDate());

    }



}

 

class RssItem

package kr.co.braverokmc.rss;

import java.io.Serializable;

/**
 * Created by choi on 2017-04-15.
 */

public class RssItem implements Serializable {

    String title;
    String link;
    String description;
    String dcDate;
    String author;


    public RssItem() {
    }

    public RssItem(String title, String link, String description, String dcDate, String author) {
        this.title = title;
        this.link = link;
        this.description = description;
        this.dcDate = dcDate;
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

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

    public String getLink() {
        return link;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDcDate() {
        return dcDate;
    }

    public void setDcDate(String dcDate) {
        this.dcDate = dcDate;
    }

    public String getAuthor() {
        return author;
    }

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

    @Override
    public String toString() {
        return "RssItem{" +
                "title='" + title + '\'' +
                ", link='" + link + '\'' +
                ", description='" + description + '\'' +
                ", dcDate='" + dcDate + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}

 

 

 

 

 

 

 

 

100강

 

101강

 

 

102강

 

 

103강

 

 

android

 

about author

PHRASE

Level 60  머나먼나라

훌륭한 부모의 슬하에 있으면 사랑에 넘치는 체험을 얻을 수 있다. 그것은 먼 훗 날 노년이 되더라도 없어지지 않는다. -루드비히 베토벤

댓글 ( 4)

댓글 남기기

작성