Gooday Note Scrap Source Android login
 
작성일 : 12-06-11 15:41
원격 json 파일 파싱하여 listView로 보여주기
 글쓴이 : 기리
조회 : 3,793   추천 : 0   비추천 : 0  
   http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-an… [1615]



Today we get on with our series that will connect our Android applications to internet webservices!

Next up in line: from JSON to a Listview. A lot of this project is identical to the previous post in this series so try to look there first if you have any problems. On the bottom of the post ill add the Eclipse project with the source.

For this example i made use of an already existing JSON webservice locatedhere.

This is a piece of the JSON array that gets returned:

01

{"earthquakes": [

02

    {

 

03

        "eqid": "c0001xgp",

04

        "magnitude": 8.8,

 

05

        "lng": 142.369,

06

        "src": "us",

 

07

        "datetime": "2011-03-11 04:46:23",

08

        "depth": 24.4,

 

09

        "lat": 38.322

10

  },

 

11

  {

12

        "eqid": "2007hear",

 

13

        "magnitude": 8.4,

14

        "lng": 101.3815,

 

15

        "src": "us",

16

        "datetime": "2007-09-12 09:10:26",

 

17

        "depth": 30,

18

        "lat": -4.5172

 

19

  }

20

<--more -->

 

21

 

22

]}

So how do we get this data into our application! Behold our getJSON class!

getJSON(String url)

01

public static JSONObject getJSONfromURL(String url){

02

 

 

03

    //initialize

04

    InputStream is = null;

 

05

    String result = "";

06

    JSONObject jArray = null;

 

07

 

08

    //http post

 

09

    try{

10

        HttpClient httpclient = new DefaultHttpClient();

 

11

        HttpPost httppost = new HttpPost(url);

12

        HttpResponse response = httpclient.execute(httppost);

 

13

        HttpEntity entity = response.getEntity();

14

        is = entity.getContent();

 

15

 

16

    }catch(Exception e){

 

17

        Log.e("log_tag", "Error in http connection "+e.toString());

18

    }

 

19

 

20

    //convert response to string

 

21

    try{

22

        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

 

23

        StringBuilder sb = new StringBuilder();

24

        String line = null;

 

25

        while ((line = reader.readLine()) != null) {

26

            sb.append(line + "\n");

 

27

        }

28

        is.close();

 

29

        result=sb.toString();

30

    }catch(Exception e){

 

31

        Log.e("log_tag", "Error converting result "+e.toString());

32

    }

 

33

 

34

    //try parse the string to a JSON object

 

35

    try{

36

            jArray = new JSONObject(result);

 

37