android异步向服务器请求数据

    下面就android向服务器请求数据的问题分析如下:

1、在android4.0以后的版本,主线程(UI线程)不在支持网络请求,原因大概是影响主线程,速度太慢,容易卡机,所以需要开启新的线程请求数据;

  

  1. <span style="font-family:System;font-size:12px;">thread1 = new Thread(){  
  2.             @Override  
  3.             public void run() {  
  4.                 try {  
  5.                     URL url = new URL(WebUrlManager.CARSEVER_GetCarsServlet);  
  6.                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  7.                       
  8.                     BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());  
  9.                     //缓冲读取  
  10.                     byte[] data = new byte[1024];  
  11.                     int len = 0;  
  12.                     String bufferString = "";  
  13.                     while((len = bis.read(data)) != -1){  
  14.                         bufferString+=new String(data, 0, len);  
  15.                     }  
  16.                     carList = new JSONArray(bufferString.trim());  
  17.                     //System.out.println(carList);  
  18.                     /* 
  19.                     for(int i=0;i<carList.length();i++){ 
  20.                         System.out.println("加载图片"); 
  21.                         JSONObject json = (JSONObject) carList.get(i); 
  22.                         String imageName = json.getString("image"); 
  23.                         bm = BitmapFactory.decodeStream(new URL(WebUrlManager.CARSERVER_CAR_IMAGE+imageName).openStream()); 
  24.                         carImageArray.add(bm); 
  25.                     } 
  26.                     */  
  27.                 } catch (MalformedURLException e) {  
  28.                     // TODO Auto-generated catch block  
  29.                     e.printStackTrace();  
  30.                 } catch (IOException e) {  
  31.                     // TODO Auto-generated catch block  
  32.                     e.printStackTrace();  
  33.                 } catch (JSONException e) {  
  34.                     // TODO Auto-generated catch block  
  35.                     e.printStackTrace();  
  36.                 }  
  37.                 flag = true;  
  38.             }  
  39.         };  
  40.         thread1.start();</span>  

 

 

2、新线程完成后一启动,发现报错,空指针nullpointerexception,要等待线程完毕后才能得到数据,下面是两种解决方法:

1)要么判断线程是否还活着;

2)要么在线程中设置一flag,结束后,更改其状态 

  1. <span style="font-family:System;font-size:12px;">/*  
  2.         //等待线程thread1执行完毕  
  3.         while(true){  
  4.                     if(thread1.isAlive()){  
  5.                         try {  
  6.                             Thread.sleep(500);  
  7.                         } catch (InterruptedException e) {  
  8.                             // TODO Auto-generated catch block  
  9.                             e.printStackTrace();  
  10.                         }  
  11.                     }else{  
  12.                         break;  
  13.                     }  
  14.             }  
  15.         */  
  16.         //当线程还没结束,就睡500毫秒ms  
  17.         while(!flag){  
  18.                 try {  
  19.                     Thread.sleep(500);  
  20.                 } catch (InterruptedException e) {  
  21.                     // TODO Auto-generated catch block  
  22.                     e.printStackTrace();  
  23.             }  
  24.         }  
  25.               
  26.     }</span>  


3、处理返回的json数据

 

1)向服务器请求Json数据,保存在carList 

  1. <span style="font-family:System;font-size:12px;">URL url = new URL(WebUrlManager.CARSEVER_GetCarsServlet);  
  2.                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  3.                       
  4.                     BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());  
  5.                     //缓冲读取  
  6.                     byte[] data = new byte[1024];  
  7.                     int len = 0;  
  8.                     String bufferString = "";  
  9.                     while((len = bis.read(data)) != -1){  
  10.                         bufferString+=new String(data, 0, len);  
  11.                     }  
  12.                     carList = new JSONArray(bufferString.trim());</span>  


2)解析Json数据

  

  1. <span style="font-family:System;font-size:12px;">JSONObject car = (JSONObject) getItem(position);  
  2.         try {  
  3.             //this.pic.setImageBitmap(carImageArray.get(position));  
  4.             this.title.setText(car.getString("title"));  
  5.             this.describe.setText(car.getString("describe"));  
  6.             this.updateTime.setText(car.getString("updateTime"));  
  7.             this.price.setText(String.format("%.1f", car.getDouble("price"))+"万");  
  8.             this.pic.setTag(WebUrlManager.CARSERVER_CAR_IMAGE+car.getString("image"));  
  9.             new AsyncViewTask().execute(this.pic);  
  10.         } catch (JSONException e1) {  
  11.             e1.printStackTrace();  
  12.         }</span>  


4、图片加载通常很慢,最好异步请求

 

1)先贴出异步请求的类源代码 

  1. <span style="font-family:System;font-size:12px;">import java.io.InputStream;  
  2. import java.lang.ref.SoftReference;  
  3. import java.net.HttpURLConnection;  
  4. import java.net.URL;  
  5. import java.util.HashMap;  
  6. import android.graphics.drawable.Drawable;  
  7. import android.os.AsyncTask;  
  8. import android.util.Log;  
  9. import android.view.View;  
  10. import android.webkit.URLUtil;  
  11. import android.widget.ImageView;  
  12.    
  13. /** 
  14.  * @author wzy qq:290581825  http://blog.csdn.net/wzygis 
  15.  */  
  16. public class AsyncViewTask extends AsyncTask<View, Void, Drawable> {  
  17.     private View mView;  
  18.     private HashMap<String, SoftReference<Drawable>> imageCache;  
  19.   
  20.     public AsyncViewTask() {  
  21.         imageCache = new HashMap<String, SoftReference<Drawable>>();  
  22.     }  
  23.    
  24.     protected Drawable doInBackground(View... views) {  
  25.         Drawable drawable = null;  
  26.         View view = views[0];  
  27.         if (view.getTag() != null) {  
  28.             if (imageCache.containsKey(view.getTag())) {  
  29.                 SoftReference<Drawable> cache = imageCache.get(view.getTag().toString());  
  30.                 drawable = cache.get();  
  31.                 if (drawable != null) {  
  32.                     return drawable;  
  33.                 }  
  34.             }  
  35.             try {  
  36.                 if (URLUtil.isHttpUrl(view.getTag().toString())) {// 如果为网络地址。则连接url下载图片  
  37.                     URL url = new URL(view.getTag().toString());  
  38.                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  39.                     conn.setDoInput(true);  
  40.                     conn.connect();  
  41.                     InputStream stream = conn.getInputStream();  
  42.                     drawable = Drawable.createFromStream(stream, "src");  
  43.                     stream.close();  
  44.                 } else {// 如果为本地数据,直接解析  
  45.                     drawable = Drawable.createFromPath(view.getTag().toString());  
  46.                 }  
  47.             } catch (Exception e) {  
  48.                 Log.v("img", e.getMessage());  
  49.                 return null;  
  50.             }  
  51.         }  
  52.         this.mView = view;  
  53.         return drawable;  
  54.     }  
  55.    
  56.     protected void onPostExecute(Drawable drawable) {  
  57.         if (drawable != null) {  
  58.             ImageView view = (ImageView) this.mView;  
  59.             view.setImageDrawable(drawable);  
  60.             this.mView = null;  
  61.         }  
  62.     }  
  63.    
  64. }</span>  

 

结果如下:

posted @ 2014-03-03 09:51  安卓吧  阅读(13758)  评论(0编辑  收藏  举报