標籤: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 從伺服器擷取新聞資料並顯示在用戶端