RSS를 가져와서 정리 하는 방법임.
실제로 코드를 만들 때에는 이해하면서 왔다갔다 해야하지만 설명이 힘드므로 완성코드만 올릴테니 순서상관없이 붙여넣기하기.
00. 화면구성을 다음과 같이 한다.
<?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: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"
tools:context="com.example.joey.myhttp.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://www.chosun.com/site/data/rss/sports.xml"
android:id="@+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="@+id/button"
android:layout_toStartOf="@+id/button"
android:layout_above="@+id/scrollView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RSS 가져오기"
android:id="@+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="button01"
android:layout_alignParentTop="true" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="140dp"
android:text="New Text"
android:background="#ffeeddcc"
android:layout_centerHorizontal="true"
android:layout_below="@+id/button"
android:id="@+id/scrollView">
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView" />
</RelativeLayout>
01. 자바위에 마우스오른쪽버튼 -> New -> JavaClass 클릭하여 새로운 클래스를 만든다.
02. RssItem 이라고 만들고 OK.
03. 내용을 채워보자.
package com.example.joey.myrss;
public class RssItem {
String title;
String link;
String description;
String image;
String dcDate;
public RssItem(){ //생성자
}
public RssItem(String title, String link, String description, String image, String dcDate){
this.title = title;
this.link = link;
this.description = description;
this.image = image;
this.dcDate = dcDate;
}
/* Getter and Setter 를 이용 */
public String getDcDate() {
return dcDate;
}
public void setDcDate(String dcDate) {
this.dcDate = dcDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
04. 메인스크립트를 입력해보자.
package com.example.joey.myrss;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
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 {
EditText editText;
TextView textView;
Handler handler = new Handler();
@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.textView2);
}
public void button01(View v) {
RequestThread thread = new RequestThread();
thread.start();
}
class RequestThread extends Thread {
public void run() {
try {
String urlStr = editText.getText().toString();
println("요청 URL : " + urlStr);
URL url = new URL(urlStr);
HttpURLConnection urconn = (HttpURLConnection) url.openConnection();
urconn.setDoInput(true);
urconn.setDoOutput(true);
urconn.setConnectTimeout(15000); // 15초
int resCode = urconn.getResponseCode();
println("응답 코드 : " + resCode);
if (resCode == HttpURLConnection.HTTP_OK) {
InputStream instream = urconn.getInputStream();
parseRss(instream);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void parseRss(InputStream instream)
throws Exception {
println("parseRSS() 호출됨");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(instream);
ArrayList<RssItem> itemList = parseDocument(document);
println("파싱된 아이템의 갯수 : " + itemList.size());
}
private ArrayList<RssItem> parseDocument(Document document) {
Element elem = document.getDocumentElement();
NodeList nodeList = elem.getElementsByTagName("item");
ArrayList<RssItem> itemList = new ArrayList<RssItem>();
if (nodeList != null) {
for (int i = 0; i < nodeList.getLength(); i++) {
RssItem item = parseItemNode(nodeList, i);
itemList.add(item);
}
}
return itemList;
}
private RssItem parseItemNode(NodeList nodeList, int index) {
Element elem = (Element) nodeList.item(index);
Element titleElem = (Element) elem.getElementsByTagName("title").item(0);
Element linkElem = (Element) elem.getElementsByTagName("link").item(0);
Element descriptionElem = (Element) elem.getElementsByTagName("description").item(0);
Element imageElem = (Element) elem.getElementsByTagName("image").item(0);
Element dcdateElem = (Element) elem.getElementsByTagName("dc:date").item(0);
String title = "";
if (titleElem != null) {
Node firstChild = titleElem.getFirstChild();
if (firstChild != null) {
title = firstChild.getNodeValue();
}
}
String link = "";
if (linkElem != null) {
Node firstChild = linkElem.getFirstChild();
if (firstChild != null) {
link = firstChild.getNodeValue();
}
}
String description = "";
if (descriptionElem != null) {
Node firstChild = descriptionElem.getFirstChild();
if (firstChild != null) {
description = firstChild.getNodeValue();
}
}
String image = "";
if (imageElem != null) {
Node firstChild = imageElem.getFirstChild();
if (firstChild != null) {
image = firstChild.getNodeValue();
}
}
String dcDate = "";
if (dcdateElem != null) {
Node firstChild = dcdateElem.getFirstChild();
if (firstChild != null) {
dcDate = firstChild.getNodeValue();
}
}
//↓ RSSItem JAVA를 만든후 그것을 array를 이용해서 담겠다.
RssItem item = new RssItem(title, link, description, image, dcDate);
return item;
}
private void println(final String data) {
handler.post(new Runnable() {
@Override
public void run() {
textView.append(data + "\n");
}
});
}
}
05. 실행시켜서 버튼을 눌러본다.
06. 원하는 값 도출됨을 확인 할 수 있다.