android非同步向伺服器請求資料

來源:互聯網
上載者:User

    下面就android向伺服器請求資料的問題分析如下:

1、在android4.0以後的版本,主線程(UI線程)不在支援網路請求,原因大概是影響主線程,速度太慢,容易卡機,所以需要開啟新的線程請求資料;

thread1 = new Thread(){@Overridepublic void run() {try {URL url = new URL(WebUrlManager.CARSEVER_GetCarsServlet);HttpURLConnection conn = (HttpURLConnection) url.openConnection();BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());//緩衝讀取byte[] data = new byte[1024];int len = 0;String bufferString = "";while((len = bis.read(data)) != -1){bufferString+=new String(data, 0, len);}carList = new JSONArray(bufferString.trim());//System.out.println(carList);/*for(int i=0;i<carList.length();i++){System.out.println("載入圖片");JSONObject json = (JSONObject) carList.get(i);String imageName = json.getString("image");bm = BitmapFactory.decodeStream(new URL(WebUrlManager.CARSERVER_CAR_IMAGE+imageName).openStream());carImageArray.add(bm);}*/} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}flag = true;}};thread1.start();

2、新線程完成後一啟動,發現報錯,null 指標nullpointerexception,要等待線程完畢後才能得到資料,下面是兩種解決方案:

1)要麼判斷線程是否還活著;

2)要麼線上程中設定一flag,結束後,更改其狀態

/*//等待線程thread1執行完畢while(true){if(thread1.isAlive()){try {Thread.sleep(500);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}else{break;}}*///當線程還沒結束,就睡500毫秒mswhile(!flag){try {Thread.sleep(500);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

3、處理返回的json資料

1)向伺服器請求Json資料,儲存在carList

URL url = new URL(WebUrlManager.CARSEVER_GetCarsServlet);HttpURLConnection conn = (HttpURLConnection) url.openConnection();BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());//緩衝讀取byte[] data = new byte[1024];int len = 0;String bufferString = "";while((len = bis.read(data)) != -1){bufferString+=new String(data, 0, len);}carList = new JSONArray(bufferString.trim());

2)解析Json資料

JSONObject car = (JSONObject) getItem(position);try {//this.pic.setImageBitmap(carImageArray.get(position));this.title.setText(car.getString("title"));this.describe.setText(car.getString("describe"));this.updateTime.setText(car.getString("updateTime"));this.price.setText(String.format("%.1f", car.getDouble("price"))+"萬");this.pic.setTag(WebUrlManager.CARSERVER_CAR_IMAGE+car.getString("image"));new AsyncViewTask().execute(this.pic);} catch (JSONException e1) {e1.printStackTrace();}

4、圖片載入通常很慢,最好非同步請求

1)先貼出非同步請求的類原始碼

import java.io.InputStream;import java.lang.ref.SoftReference;import java.net.HttpURLConnection;import java.net.URL;import java.util.HashMap;import android.graphics.drawable.Drawable;import android.os.AsyncTask;import android.util.Log;import android.view.View;import android.webkit.URLUtil;import android.widget.ImageView; /** * @author wzy qq:290581825  http://blog.csdn.net/wzygis */public class AsyncViewTask extends AsyncTask<View, Void, Drawable> {    private View mView;    private HashMap<String, SoftReference<Drawable>> imageCache;    public AsyncViewTask() {        imageCache = new HashMap<String, SoftReference<Drawable>>();    }     protected Drawable doInBackground(View... views) {        Drawable drawable = null;        View view = views[0];        if (view.getTag() != null) {            if (imageCache.containsKey(view.getTag())) {                SoftReference<Drawable> cache = imageCache.get(view.getTag().toString());                drawable = cache.get();                if (drawable != null) {                    return drawable;                }            }            try {                if (URLUtil.isHttpUrl(view.getTag().toString())) {// 如果為網路地址。則串連url下載圖片                    URL url = new URL(view.getTag().toString());                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();                    conn.setDoInput(true);                    conn.connect();                    InputStream stream = conn.getInputStream();                    drawable = Drawable.createFromStream(stream, "src");                    stream.close();                } else {// 如果為本機資料,直接解析                    drawable = Drawable.createFromPath(view.getTag().toString());                }            } catch (Exception e) {                Log.v("img", e.getMessage());                return null;            }        }        this.mView = view;        return drawable;    }     protected void onPostExecute(Drawable drawable) {        if (drawable != null) {            ImageView view = (ImageView) this.mView;            view.setImageDrawable(drawable);            this.mView = null;        }    } }


結果如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.