新聞客戶端案例
第一次進入新聞客戶端需要請求服務器獲取新聞數據,做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。