본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/Open API

Android Studio Open API 2

by 차누감 2019. 9. 20.
반응형

내 앱안에 xml이 있다는 전제로 간단한 예제를 만들어보자.

다음 예제 android Studio Open API 3(원래는 예로 기상청pc에서 xml을 가져와서 분석하여 Activity UI로 보여줘야한다.)

지금 예제(지금은 xml가져오는건 안하고 Activity UI로 보여주는 것을 먼저 연습한다.)

<실행 화면>

우선 xml을 만들어보자.

 

movies.xml 코드 내용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="utf-8"?>
<movie>
    <item>
        <no>1</no>
        <title>Alien</title>
        <genre>SF, action, adventure</genre>
    </item>
 
    <item>
        <no>2</no>
        <title>avatar</title>
        <genre>SF, action, adventure</genre>
    </item>
 
    <item>
        <no>3</no>
        <title>Notting Hill</title>
        <genre>romance, melo</genre>
    </item>
 
    <item>
        <no>4</no>
        <title>Nightmare</title>
        <genre>horror, thriller</genre>
    </item>
 
</movie>
 
 
 

<> 태그 내용은 임의로 작성한 것임 (movie, no,tile,genre 이런거 임의로 그냥 쓴것, 변수명처럼!!)

왜냐면 나중에 보여주는 화면이

번호 :1

제목 : Alien 

장르 : SF               이런식으로 보여줄 것이기 때문에....

 

화면을 구성해보자. (버튼을 누르면 그냥 TextView에 보여줄 것이다.)

activity_main.xml 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
 
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="load XML data"
        android:onClick="clickBtn"/>
 
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp"/>
 
 
</LinearLayout>
 
 
 

화면 구성

이제 메인 코드를 작성해보자.

MainActivity.java 코드

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
 
 
 
import org.xmlpull.v1.XmlPullParserException;
 
 
public class MainActivity extends AppCompatActivity {
 
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        tv= findViewById(R.id.tv);
    }
 
    public void clickBtn(View view) {
        //Resources폴더 안에 있는 xml문서를 읽어와서 분석(parse)하는 작업 수행
 
        //res폴더 관리자 객체 소환
        Resources res= getResources();
 
        //창고 관리자로 부터 파서객체(분석가) 얻어오기
        XmlResourceParser xrp= res.getXml(R.xml.movies);
 
        StringBuffer buffer= new StringBuffer();
 
        //xml파서에게 xml문서를 분석하도록 코딩
        //xmlParser는 1)START_DOCUMENT 2)START_TAG 3)TEXT 4)END_TAG 5)END_DOCUMENT 로 구분
 
        try {
            xrp.next();
            int eventType=xrp.getEventType();
 
            String tagName; //태그 이름
            String text;    //내용 글씨
 
            while (eventType!=XmlResourceParser.END_DOCUMENT){
 
                switch(eventType){
                    case XmlResourceParser.START_DOCUMENT:
                        buffer.append("xml 파싱 시작합니다..\n\n");
                        break;
 
                    case XmlResourceParser.START_TAG:
                        tagName= xrp.getName(); //태그문의 이름 얻어오기
 
                        if(tagName.equals("no")){
                            buffer.append("번호:");
                        }else if(tagName.equals("title")){
                            buffer.append("제목:");
                        }else if(tagName.equals("genre")){
                            buffer.append("장르:");
                        }
                        break;
 
                    case XmlResourceParser.TEXT:
                        text= xrp.getText();
                        buffer.append(text);
                        break;
 
                    case XmlResourceParser.END_TAG:
                        tagName= xrp.getName();
                        if(tagName.equals("no")){
                            buffer.append("\n");
                        }else if(tagName.equals("title")){
                            buffer.append("\n");
                        }else if(tagName.equals("genre")){
                            buffer.append("\n");
                        }else if(tagName.equals("item")){
                            buffer.append("\n");
                        }
                        break;
 
                    case XmlResourceParser.END_DOCUMENT:
                        break;
                }//switch
                eventType=xrp.next();   //next를 하면 evetType을 준다.
            }//while
 
            buffer.append("파싱 종료 ....");
            tv.setText(buffer.toString());
 
        } catch (IOException e) {e.printStackTrace();} catch (XmlPullParserException e) {e.printStackTrace();}
    }// clickBtn() ..
}//MainActivity class ..
 
 
 

 

 

<실행 화면>

버튼을 누르면 xml 내용이 보여진다.

 

반응형

댓글