android 從伺服器擷取新聞資料並顯示在用戶端

來源:互聯網
上載者:User

標籤:title   roi   返回   util   娛樂   tco   tostring   伺服器   except   

新聞用戶端案例

第一次進入新聞用戶端需要請求伺服器擷取新聞資料,做listview的展示,
為了第二次再次開啟新聞用戶端時能快速顯示新聞,需要將資料緩衝到資料庫中,下次開啟可以直接去資料庫中擷取新聞直接做展示。

總體步驟:
  1.寫布局listview ok

  2.找到listview,設定條目的點擊事件。 ok

  3.擷取資料提供給listview做展示。

    3.1:擷取本機資料庫緩衝的新聞資料,讓listview顯示。如果沒有網路不至於顯示空介面。
    3.2:請求伺服器擷取新聞資料,是一個json字串,需要解析json,封裝到list集合中。提供給listview展示。

public static String newsPath_url = "xxxx";
//封裝新聞的假資料到list中返回
public static ArrayList<NewsBean> getAllNewsForNetWork(Context context) {
ArrayList<NewsBean> arrayList = new ArrayList<NewsBean>();
try{
//1.請求伺服器擷取新聞資料
//擷取一個url對象,通過url對象得到一個urlconnnection對象
URL url = new URL(newsPath_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//設定串連的方式和逾時時間
connection.setRequestMethod("GET");
connection.setConnectTimeout(10*1000);
//擷取請求響應碼
int code = connection.getResponseCode();
if(code == 200){
//擷取請求到的流資訊
InputStream inputStream = connection.getInputStream();
String result = StreamUtils.streamToString(inputStream);

//2.解析擷取的新聞資料到List集合中。

JSONObject root_json = new JSONObject(result);//將一個字串封裝成一個json對象。
JSONArray jsonArray = root_json.getJSONArray("newss");//擷取root_json中的newss作為jsonArray對象

for (int i = 0 ;i < jsonArray.length();i++){//迴圈遍曆jsonArray
JSONObject news_json = jsonArray.getJSONObject(i);//擷取一條新聞的json

NewsBean newsBean = new NewsBean();

newsBean. id = news_json.getInt("id");
newsBean. comment = news_json.getInt("comment");//評論數
newsBean. type = news_json.getInt("type");//新聞的類型,0 :頭條 1 :娛樂 2.體育
newsBean. time = news_json.getString("time");
newsBean. des = news_json.getString("des");
newsBean. title = news_json.getString("title");
newsBean. news_url = news_json.getString("news_url");
newsBean. icon_url = news_json.getString("icon_url");

arrayList.add(newsBean);

}

//3.清楚資料庫中舊的資料,將新的資料緩衝到資料庫中
new NewsDaoUtils(context).delete();
new NewsDaoUtils(context).saveNews(arrayList);
}

}catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}

    3.3: 擷取服務端資料成功後,需要緩衝到本機資料庫,緩衝前需要清空本機資料庫。

  4.建立一個Adapter繼承BaseAdapter,封裝4個方法,需要接收穫取的新聞資料 


  5.將adapter設定給listview。 

android 從伺服器擷取新聞資料並顯示在用戶端

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.