1、在android4.0以后的版本,主線程(UI線程)不在支持網絡請求,原因大概是影響主線程,速度太慢,容易卡機,所以需要開啟新的線程請求數據;
2、新線程完成后一啟動,發現報錯,空指針 nullpointerexception,要等待線程完畢后才能得到數據,下面是兩種解決方法:
1)要么判斷線程是否還活著;
2)要么在線程中設置一flag,結束后,更改其狀態
3、處理返回的json數據
1)向服務器請求Json數據,保存在carList
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數據
4、圖片加載通常很慢,最好異步請求
異步請求類源代碼
public AsyncViewTask() {
imageCache = new HashMap>();
}
protected Drawable doInBackground(View... views) {
Drawable drawable = null;
View view = views[0];
if (view.getTag() != null) {
if (imageCache.containsKey(view.getTag())) {
SoftReference 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;
}}}
新聞熱點
疑難解答
圖片精選