RSS를 가져와서 리스트뷰 처리 하는 방법임.
지난번 강좌 참조: https://asterisco.tistory.com/62
00. 저번 코드중에 메인스크립의 리스트뷰속성을 스크롤바 아래로 내리는 코드한줄 추가.!
android:layout_below="@+id/scrollView"
01. res 아래있는 레이아웃 디렉터리에서 마우스오른쪽버튼 클릭->New->LayoutResourceFile 클릭
02. 이름을 적당이 부여하고 OK버튼 클릭. (rss_item.xml로 주었다.)
03. rss_item.xml에 대한 모양은 다음과 같다. 리스트뷰의 모양을 잡아주는 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">
<ImageView
android:id="@+id/imageView"
android:layout_width="120dp"
android:layout_height="120dp"
android:background="#ffeedddd" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="26dp"/>
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textSize="20dp" />
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
04. 자카위에서 마우스오른쪽버튼 클릭->New->JavaClass 클릭.
05. 이름을 적당히 부여하고 OK버튼 클릭.! (RssItemView 라고 주었다.)
06. 코드를 입력해주자.
package com.example.joey.myrss;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class RssItemView extends LinearLayout {
ImageView imageView;
TextView textView;
TextView textView2;
TextView textView3;
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 inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.rss_item, this, true);
imageView = (ImageView) findViewById(R.id.imageView);
textView = (TextView) findViewById(R.id.textView);
textView2 = (TextView) findViewById(R.id.textView2);
textView3 = (TextView) findViewById(R.id.textView3);
}
public void setRssItem(RssItem item){
String title = item.getTitle();
textView.setText(title);
String dcDate = item.getDcDate();
textView2.setText(dcDate);
String description = item.getDescription();
textView3.setText(description);
}
}
07. 메인스크립트로와서 새로운부분을 추가해준다.
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.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
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();
ListView listView;
RssAdapter rssAdapter;
@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);
listView = (ListView) findViewById(R.id.listView);
rssAdapter = new RssAdapter();
listView.setAdapter(rssAdapter);
}
class RssAdapter extends BaseAdapter{
ArrayList<RssItem> itemList = new ArrayList<RssItem>();
public void setItemList(ArrayList<RssItem> itemList){
this.itemList = itemList;
}
@Override
public int getCount() {
return itemList.size();
}
@Override
public Object getItem(int position) {
return itemList.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(getApplicationContext());
} else{
view = (RssItemView) convertView;
}
view.setRssItem(itemList.get(position));
return view;
}
}
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);
final ArrayList<RssItem> itemList = parseDocument(document);
println("파싱된 아이템의 갯수 : " + itemList.size());
handler.post(new Runnable() {
@Override
public void run() {
rssAdapter.setItemList(itemList);
rssAdapter.notifyDataSetChanged();
}
});
}
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");
}
});
}
}
08. 실행시켜본다.
09. 버튼을 눌러 구동시켜본다.
10. 정상작동을 확인하자.