android异步向服务器请求数据

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

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

thread1 = new Thread(){
			@Override
			public 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 block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				flag = true;
			}
		};
		thread1.start();

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

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

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

/*
		//等待线程thread1执行完毕
		while(true){
					if(thread1.isAlive()){
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}else{
						break;
					}
			}
		*/
		//当线程还没结束,就睡500毫秒ms
		while(!flag){
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.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;
        }
    }
 
}


结果如下:


android异步向服务器请求数据,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。