標籤:
1、下載資料來建立一個實體類
class MyData { String imagepath; String title; String desc; public MyData(String imagepath, String title, String desc) { super(); this.imagepath = imagepath; this.title = title; this.desc = desc; } }
2、AsyncTask資料載入及Json解析類
class FileAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { InputStream is = null; ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(4000); try { URL url = new URL(params[0]); URLConnection openConnection = url.openConnection(); //設定連線逾時的時間 openConnection.setConnectTimeout(3000); //資料讀取逾時的時間 openConnection.setReadTimeout(3000); is = openConnection.getInputStream(); byte[] buffer = new byte[1024]; int len; while (-1 != (len = is.read(buffer))) { byteArrayBuffer.append(buffer, 0, len); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block runOnUiThread(new Runnable() { public void run() { //設定載入異常時的控制項,通常顯示運行進度條 } }); e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } String res = new String(byteArrayBuffer.toByteArray(), 0, byteArrayBuffer.length()); return res; } // 解析jsonArray資料 @Override protected void onPostExecute(String result) { try { JSONArray jsonArray = new JSONArray(result); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String imagepath = jsonObject.getString("imagepath"); String title = jsonObject.getString("title"); String desc = jsonObject.getString("desc"); MyData myData = new MyData(imagepath, title, desc); dataList.add(myData);//加入資料 } myAdapter.notifyDataSetChanged();//通知適配器資料改變 } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } super.onPostExecute(result); } }
3、調用
private ArrayList<MyData> dataList = new ArrayList<MainActivity.MyData>();//聲明全域變數dataList FileAsyncTask fileAsyncTask = new FileAsyncTask(); fileAsyncTask.execute("http://192.168.56.1:8080/service.txt");
著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。
Android資料載入和Json解析——藍本