Android簡單的獲取網絡上的json文件

設置網絡訪問權限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.wangjialin.internet.json"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />
<!-- 訪問internet權限 -->
<uses-permission android:name="android.permission.INTERNET"/>

</manifest> 

佈局文件:
mian.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<ListView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/listView"
    />
</LinearLayout>

佈局文件:
item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">

  <TextView
   android:layout_width="200dp"
   android:layout_height="wrap_content"
   android:id="@+id/title"
  />

    <TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/timelength"
  />
</LinearLayout>

編寫主MainActivity文件,具體內容如下:

package com.wangjialin.internet.json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.wangjialin.internet.json.domain.News;
import com.wangjialin.internet.json.service.NewsService;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView listView = (ListView) this.findViewById(R.id.listView);

        String length = this.getResources().getString(R.string.length);
        try {
            List<News> newes = NewsService.getJSONLastNews();
            List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
            for(News news : newes){
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("id", news.getId());
                item.put("title", news.getTitle());
                item.put("timelength", length+ news.getTimelength());
                data.add(item);
            }
            SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
                    new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength});
            listView.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

MainActivity 的核心功能是獲取數據並顯示數據。
其中獲取的數據內的NewsService的具體內容如下:

package com.wangjialin.internet.json.service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.wangjialin.internet.json.domain.News;
import com.wangjialin.internet.json.utils.StreamTool;



public class NewsService {

    /**
     * 獲取最新視頻資訊
     * @return
     * @throws Exception
     */
    public static List<News> getJSONLastNews() throws Exception{
        String path = "http://192.168.1.100:8080/ServerForJSON/NewsListServlet";
        HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode() == 200){
            InputStream json = conn.getInputStream();
            return parseJSON(json);
        }
        return null;
    }

    private static List<News> parseJSON(InputStream jsonStream) throws Exception{
        List<News> list = new ArrayList<News>();
        byte[] data = StreamTool.read(jsonStream);
        String json = new String(data);
        JSONArray jsonArray = new JSONArray(json);
        for(int i = 0; i < jsonArray.length() ; i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            int id = jsonObject.getInt("id");
            String title = jsonObject.getString("title");
            int timelength = jsonObject.getInt("timelength");
            list.add(new News(id, title, timelength));
        }
        return list;
    }
}

在getJSONLastNews方法中是直接請求搭建好的web服務器,獲取JSON輸入流後,使用parseJSON方法解析XML數據並最終返回集合數據。
同時在NewsService中用到了一個JavaBean,用於封裝XML數據,其名稱News,具體內容如下所示:

package com.wangjialin.internet.json.domain;

public class News {
    private Integer id;
    private String title;
    private Integer timelength;
    public News(){}
    public News(Integer id, String title, Integer timelength) {
        this.id = id;
        this.title = title;
        this.timelength = timelength;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public Integer getTimelength() {
        return timelength;
    }
    public void setTimelength(Integer timelength) {
        this.timelength = timelength;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章