一:
首先ListView的网络数据加载一直是难题在Android的学习过程中,因为设计到了各种回调方法以及包括Adapter、AsyncTask、网络加载、json数据的解析
二:
于是可以分析得出需要构建以下几个包及其包含的类:
bean(包)--->Shop(用来封装json数据中的属性的,里面写的是构造函数和Getter和Setter)
utils(工具包)--->HttpUtils(工具类:用来将传入的String类型的网址转换成byte[]然后返回。)
utils(工具包)--->ParserJson(工具类:用来将传入的jsonString字符串转换成list的list集合返回)
AsyncTask(异步任务包)---->DownLoadAsyncTask(用来进行耗时操作的.其中两个方法doInBackground是将传入的
api接口的网址,通过网络解析工具类HttpUtils得到一个bye[]数组,再将byte[]数组通过:
byte[] buff=HttpUils.getHttpResult(params[0]);
String jsOnString=new String(buff,0,buff.length);
即可以得到:一个json解析后的list集合。再将list回传。在onPostExecute方法中,将list集合进行适配器的适配,所以需要构建一个Adapter了。
adapter(工具包)--->MyBaseAdapter(继承自baseAdapter,在其中有四个方法,最为重要的是getView方法,在这个方法中需要注意的是,首先需要对holder的属性进行实例化,调用方法为LayoutInflater,然后再setTag(holder),再需要进行的是将文字和图片set到item里面,由于需要用将图片下载进行set,所以需要再开启一个异步任务LoadImageAsyncTask,然后返回convertView)
AsyncTask(异步任务包)---->LoadImageAsyncTask(用来将传入的图片的网址转换成图片进行回传到MyBaseAdapter里面,所以需要将数据回传,构建一个CallBack的回调函数,将得到的bitmap图片回传到MyBaseAdapter。)
----然后DownLoadAsyncTask在onPostExecute方法中传入一个listView的实例化对象lv,进行lv.setAdapter(adapter);
----再在主函数中进行最后一步即可,开启DownLoadAsyncTask异步任务。
即有代码:
在MainActivity中:
package com.example.administrator.firstapp;在adapter中:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import asyncTask.DownloadAsyncTask;
import bean.Shop;
public class MainActivity extends AppCompatActivity {
private ListView lv;
private Listlist=new ArrayList ();
private String path="http://moblist.baobeigezi.com/v26/m_recommend_product/get_hot_sale_list?page=1&category_id=28&size=15&sign=c06c5b87a9db0a907774f1a094eee819&session_id=&v=2.6.9&c=AppStore&agent=ios&local_cart_id=838618F5-24B3-4356-904D-";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.lv);
new DownloadAsyncTask(this,list,lv).execute(path);
}
}
package adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.administrator.firstapp.R;
import java.util.List;
import asyncTask.LoadImageAsyncTask;
import bean.Shop;
import utils.HttpUtils;
/**
* Created by Administrator on 2016/8/22.
*/
public class MyBaseAdapter extends BaseAdapter {
private Listlist;
private Context context;
private ListView lv;
public MyBaseAdapter(Listlist, Context context,ListView lv) {
this.list = list;
this.cOntext= context;
this.lv=lv;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
ViewHolder holder=new ViewHolder();
public View getView(int position, View convertView, ViewGroup parent) {
if (cOnvertView==null){
LayoutInflater layoutInflater=LayoutInflater.from(context);
cOnvertView=layoutInflater.inflate(R.layout.activity_item_last,null);
holder.iv= (ImageView) convertView.findViewById(R.id.iv_image_url);
holder.tv_market_price= (TextView) convertView.findViewById(R.id.tv_market_price);
holder.tv_store_price= (TextView) convertView.findViewById(R.id.tv_store_price);
holder.tv_name= (TextView) convertView.findViewById(R.id.tv_name);
convertView.setTag(holder);
}
else {
holder= (ViewHolder) convertView.getTag();
}
holder.tv_name.setText(list.get(position).getName());
holder.tv_store_price.setText(list.get(position).getMarket_price());
holder.tv_market_price.setText(list.get(position).getMarket_price());
new LoadImageAsyncTask(context, new LoadImageAsyncTask.CallBack() {
@Override
public void sendImage(Bitmap bm) {
holder.iv.setImageBitmap(bm);
}
}).execute(list.get(position).getImage_url());
return convertView;
}
static class ViewHolder{
ImageView iv;
TextView tv_market_price,tv_store_price,tv_name;
}
}
package asyncTask;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import adapter.MyBaseAdapter;
import bean.Shop;
import utils.HttpUtils;
import utils.ParserJson;
/**
* Created by Administrator on 2016/8/22.
*/
public class DownloadAsyncTask extends AsyncTask> {
private Context context;
private Listlist;
private ListView lv;
public DownloadAsyncTask(Context context, Listlist, ListView lv) {
this.cOntext= context;
this.list = list;
this.lv = lv;
}
@Override
protected ListdoInBackground(String... params) {
if (HttpUtils.isNetWork(context)){
byte[] buff=HttpUtils.getHttpResult(params[0]);
String jsOnString= new String(buff,0,buff.length);
list=ParserJson.parserJsonToList(jsonString);
}
return list;
}
@Override
protected void onPostExecute(Listresult) {
if (result!=null&&result.size()!=0){
list.addAll(result);
MyBaseAdapter adapter=new MyBaseAdapter(list,context,lv);
lv.setAdapter(adapter);
}
else {
Toast.makeText(context, "下载异常", Toast.LENGTH_SHORT);
}
}
}
package asyncTask;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import utils.HttpUtils;
/**
* Created by Administrator on 2016/8/22.
*/
public class LoadImageAsyncTask extends AsyncTask{
private Context context;
private byte[] buff;
private CallBack cb;
private Bitmap bit;
public LoadImageAsyncTask(Context context,CallBack cb) {
this.cOntext= context;
this.cb = cb;
}
@Override
protected byte[] doInBackground(String... params) {
if (HttpUtils.isNetWork(context)){
buff =HttpUtils.getHttpResult(params[0]);
Log.i("TAG",buff.toString());
}
return buff;
}
@Override
protected void onPostExecute(byte[] result) {
if(result!=null&&result.length!=0){
Bitmap bm =BitmapFactory.decodeByteArray(result,0,result.length);
cb.sendImage(bm);
}
}
public interface CallBack{
public void sendImage(Bitmap bm);
}
}
package bean;
/**
* Created by Administrator on 2016/8/22.
*/
/*{
"code": 1,
"msg": "成功!",
"data": {
"product_list": [
{
"product_id": "29532",
"market_price": "336.00",
"store_price": "145.00",
"name": "【包邮包税】新西兰A2 Platinum酪蛋白婴儿3段奶粉(1-3周岁宝宝)900g 【保质期2018年3月】",
"image_url": "http://image.baoimg.net/photo/201606/2016061310003240007625.jpg",*/
public class Shop {
private String market_price;
private String store_price;
private String name;
private String image_url;
public Shop(String market_price, String store_price, String name, String image_url) {
this.market_price = market_price;
this.store_price = store_price;
this.name = name;
this.image_url = image_url;
}
public String getMarket_price() {
return market_price;
}
public void setMarket_price(String market_price) {
this.market_price = market_price;
}
public String getStore_price() {
return store_price;
}
public void setStore_price(String store_price) {
this.store_price = store_price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
}
package utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Administrator on 2016/8/21.
*/
public class HttpUtils {
public static boolean isNetWork(Context context){
ConnectivityManager manager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info=manager.getActiveNetworkInfo();
if (info!=null){
return info.isConnected();
}
else {
return false;
}
}
public static byte[] getHttpResult(String path){
ByteArrayOutputStream os=new ByteArrayOutputStream();
try {
URL url=new URL(path);
HttpURLConnection cOnn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int respOnseCode=conn.getResponseCode();
if(respOnseCode==200){
InputStream in=conn.getInputStream();
int temp=0;
byte[] buff=new byte[1024];
while ((temp=in.read(buff))!=-1){
os.write(buff,0,temp);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return os.toByteArray();
}
}
package utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import bean.Shop;
/**
* Created by Administrator on 2016/8/22.
*/
/*{
"code": 1,
"msg": "成功!",
"data": {
"product_list": [
{
"product_id": "29532",
"market_price": "336.00",
"store_price": "145.00",
"name": "【包邮包税】新西兰A2 Platinum酪蛋白婴儿3段奶粉(1-3周岁宝宝)900g 【保质期2018年3月】",
"image_url": "http://image.baoimg.net/photo/201606/2016061310003240007625.jpg",*/
public class ParserJson {
public static ListparserJsonToList(String jsonString){
Listlist= new ArrayList ();
try {
JSONObject jsOnObject=new JSONObject(jsonString);
JSONObject object=jsonObject.getJSONObject("data");
JSONArray jsOnArray=object.getJSONArray("product_list");
for (int i=0;iJSONObject obj=jsonArray.getJSONObject(i);
String market_price=obj.getString("market_price");
String store_price=obj.getString("store_price");
String name=obj.getString("name");
String image_url=obj.getString("image_url");
Shop shop=new Shop(market_price,store_price,name,image_url);
list.add(shop);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
}