728x90

이제 ListView 에 간단하게 출력하는 예제를 살펴보자.


activity_main.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" >

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#e7e7e7"
        />
</LinearLayout>


Student.java 클래스를 만든다.




이렇게 하면 파일이 완성된다.

public class Student {
    String name;
    String age;
    String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


이제 MainActivity.java 파일 코드를 구현한다.

아래 MainActivity.java 에서 case XmlPullParser.START_TAG: 부분을 살펴보자.

startTag 의 이름이 name 이면 다음 텍스트를 변수에 저장하라고 되어 있는 걸 알 수 있다.

이처럼 START_TAG 부분에서 텍스트를 어떻게 추출하는지 알 수 있다.

LOG 는 일부러 세부적으로 찍어보도록 했다. 로그를 확인하면서 어떻게 메시지를 파싱하는지 확인할 수 있다.


String startTag = xmlParser.getName();
if(startTag.equals("student")){
    student = new Student();
}
if(startTag.equals("name")){
    student.setName(xmlParser.nextText());
    Log.i(TAG,"TEXT : "+ xmlParser.getText());
    Log.i(TAG,"TEXT : "+ xmlParser.getName());
    Log.i(TAG,"TEXT : "+ student.getName());
}


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    final static String TAG ="XML";
    ListView listView;

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

        listView = (ListView) findViewById(R.id.listView);

        ArrayList<Student> list = parser();
        String[] data = new String[list.size()]; // ArrayList 크기만큼 배열 할당

        for(int i = 0; i < list.size(); i++){
            data[i] = list.get(i).getName()+" "+list.get(i).getAge()
                    +" "+list.get(i).getAddress();
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_list_item_1, data);
        listView.setAdapter(adapter);
    }

    private ArrayList<Student> parser(){
        Log.i(TAG, "parser()");
        ArrayList<Student> arrayList = new ArrayList<Student>();

        // 내부 xml파일이용시
        InputStream inputStream = getResources().openRawResource(R.raw.student);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

        XmlPullParserFactory factory = null;
        XmlPullParser xmlParser = null;

        try {
            factory = XmlPullParserFactory.newInstance();
            xmlParser = factory.newPullParser();
            xmlParser.setInput(inputStreamReader);
            Student student = null;

            int eventType = xmlParser.getEventType();

            while (eventType != XmlPullParser.END_DOCUMENT){
                switch (eventType){
                    case XmlPullParser.START_DOCUMENT:
                        Log.i(TAG, "xml START");
                        break;
                    case XmlPullParser.START_TAG:
                        Log.i(TAG, "Start TAG :" + xmlParser.getName());
                        try {
                            String startTag = xmlParser.getName();
                            if(startTag.equals("student")){
                                student = new Student();
                            }
                            if(startTag.equals("name")){
                                student.setName(xmlParser.nextText());
                                Log.i(TAG,"TEXT : "+ xmlParser.getText());
                                Log.i(TAG,"TEXT : "+ xmlParser.getName());
                                Log.i(TAG,"TEXT : "+ student.getName());
                            }
                            if(startTag.equals("age")){
                                student.setAge(xmlParser.nextText());
                                Log.i(TAG,"TEXT : "+ xmlParser.getName());
                                Log.i(TAG,"TEXT : "+ xmlParser.getName());
                                Log.i(TAG,"TEXT : "+ student.getAge());
                            }
                            if(startTag.equals("address")){
                                student.setAddress(xmlParser.nextText());
                                Log.i(TAG,"TEXT : "+ xmlParser.getName());
                                Log.i(TAG,"TEXT : "+ xmlParser.getName());
                                Log.i(TAG,"TEXT : "+ student.getAddress());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        Log.i(TAG,"End TAG : "+ xmlParser.getName());
                        String endTag = xmlParser.getName();
                        if(endTag.equals("student")){
                            arrayList.add(student);
                        }
                        break;
                }
                try {
                    eventType = xmlParser.next();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } finally{
            try{
                if(inputStreamReader !=null) inputStreamReader.close();
                if(inputStream !=null) inputStream.close();
            }catch(Exception e2){
                e2.printStackTrace();
            }
        }
        return arrayList;
    }
}


결과화면


샘플 코드 파일 첨부

xml_internaldataParsing.zip


728x90
블로그 이미지

Link2Me

,