Android data loading and Json parsing-Original Version
1. Create an object class for data download
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 data loading and Json Parsing
Class FileAsyncTask extends AsyncTask
{@ 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 (); // set the connection timeout value. setConnectTimeout (3000); // The timeout value for Data Reading 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 () {// set the control when an exception occurs. The progress bar is usually displayed.}); 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;} // parse jsonArray data @ 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); // add data} myAdapter. notifyDataSetChanged (); // notifies the adapter of data changes} catch (JSONException e) {// TODO Auto-generated catch block e. printStackTrace ();} super. onPostExecute (result );}}
3. Call
Private ArrayList
DataList = new ArrayList
(); // Declare the global variable dataList FileAsyncTask fileAsyncTask = new FileAsyncTask (); fileAsyncTask.exe cute ("http: // 192.168.56.1: 8080/service.txt ");