从服务端加载图片(Volley框架+Gson框架)


服务端代码--web.xml配置文件省略了(这些不是重点)

ShopInfo.java(为了节俭空间get、set、toString、构造器省略了)

private String name;
private String img;

ShopListServlet.java

package com.atguigu.dianpin_server.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * 获取分页ShopList的json字符串
 */
public class ShopListServlet extends HttpServlet {
	// 定义ShopInfo的集合
	private List infos;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		init();

		// count的请求参数
		int count = Integer.parseInt(request.getParameter("count"));

		// 从集合中取当前请求页的数据集合
		List data = new ArrayList();
		for (int i = 0; i < count; i++) {
			data.add(infos.get(i));
		}

		// 转换为json字符串
		String json = new Gson().toJson(data);

		// 写到客户端
		response.setContentType("text/json;charset=utf-8");
		response.getWriter().write(json);
		// 格式:[{"name":"商铺名称1",
		// "img":"f1.jpg"},{"name":"商铺名称2","img":"f12.jpg"}]
	}

	public void init() {
		if (infos == null) {
			// 创建ShopInfo的集合
			infos = new ArrayList();
			// 得到/image的真实路径
			String imagesPath = getServletContext().getRealPath("/image");
			// 创建指向图片的对象
			File dirFile = new File(imagesPath);
			// 得到file对象的数组
			File[] files = dirFile.listFiles();
			// 遍历
			for (int i = 0; i < files.length; i++) {
				// 将图片信息封装为一个shopinfo对象, 并保存到集合中
				String imageName = files[i].getName();
				String name = "商铺名称 " + (i + 1);
				infos.add(new ShopInfo(name, imageName));
			}
		}
	}

}
—————————————我是分割线——————————————————————————

首先贴出布局文件

activity_main.xml


    
    
    
    
    


list_item.xml




    

    



接下来看android代码

ShopInfo.java

(为了节俭空间get、set、toString、构造器android代码也省略了)

本类是将从服务端得到的json数组中的每个元素json对象封装为ShopInfo对象

private String name;
private String img;


VolleyTool.java

本案例需要Volley框架进行联网操作获取数据--这里提供一个工具类

package com.atguigu.day03_test;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.Volley;

public class VolleyTool {
	//初始化请求队列、图片加载器
	private RequestQueue queue;
	private ImageLoader imageLoader;

	//私有静态实例
	private static VolleyTool instance;
	//私有构造方法
	private VolleyTool(Context context) {
		//创建请求队列
		queue = Volley.newRequestQueue(context);
		//创建图片加载器
		imageLoader = new ImageLoader(queue, new LruImageCache());
	}
	//公共、静态的方法
	public static VolleyTool getInstance(Context context) {
		if (instance == null) {
			instance = new VolleyTool(context);
		}
		return instance;
	}

	//得到请求队列
	public RequestQueue getQueue() {
		return queue;
	}
	//得到图片加载器
	public ImageLoader getImageLoader() {
		return imageLoader;
	}

	/**
	 * 使用LRU回收算法的缓存类
	 */
	class LruImageCache implements ImageCache {

		// 缓存容器
		private LruCache cache;

		public LruImageCache() {
			// 计算缓存的最值
			int maxSize = (int) (Runtime.getRuntime().maxMemory() / 8);
			//创建缓存对象实例
			cache = new LruCache(maxSize) {
				@Override
				protected int sizeOf(String key, Bitmap value) {
					// 返回bitmap占用的内存大小
					return value.getRowBytes() * value.getHeight();
				}
			};
		}

		// 从缓存中取图片对象
		@Override
		public Bitmap getBitmap(String url) {
			return cache.get(url);
		}

		// 将图片对象保存到缓存容器中
		@Override
		public void putBitmap(String url, Bitmap bitmap) {
			cache.put(url, bitmap);
		}

	}
}

MainActivity.java

package com.atguigu.day03_test;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class MainActivity extends Activity {

	private ListView lv_main;
	private ProgressBar pb_main;
	//请求队列
	RequestQueue requestQueue;
	//存放数据对象的集合
	private List data = new ArrayList();
	//适配器
	private MainAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//找到对应的视图资源文件
		lv_main = (ListView) findViewById(R.id.lv_main);
		pb_main = (ProgressBar) findViewById(R.id.pb_main);
		//获取请求队列
		requestQueue = VolleyTool.getInstance(getApplicationContext()).getQueue();
		//为适配器准备加载服务端的数据
		loadData();
	}

	private void loadData() {
		String url = "http://192.168.30.41:8090/dianpin_03/ShopListServlet?count=30";

		/*注释部分是原始的解析方法
		 * new JsonArrayRequest(url, new Response.Listener() {
			@Override
			public void onResponse(JSONArray response) {
				for (int i = 0; i < response.length(); i++) {
					try {
						JSONObject jsonObject = response.getJSONObject(i);
						String name = jsonObject.getString("name");
						String img = jsonObject.getString("img");
						data.add(new ShopInfo(name, img));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {

			}
		});*/

		//创建一个请求
		Request request = new StringRequest(url, new Listener() {

				@Override
				public void onResponse(String response) {
					//将服务器端的json数组解析为ShopInfo对象集合
					data = new Gson().fromJson(response, new TypeToken>(){}.getType());
					adapter = new MainAdapter();
					//设置适配器
					lv_main.setAdapter(adapter);
					pb_main.setVisibility(View.GONE);
				}
			}, new Response.ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError error) {
	
				}
		});
		//将请求添加到队列中, 自动处理
		requestQueue.add(request);

	}
	
	class MainAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = View.inflate(getApplicationContext(),
						R.layout.list_item, null);
				holder.imageView = (NetworkImageView) convertView
						.findViewById(R.id.iv_img);
				holder.textView = (TextView) convertView
						.findViewById(R.id.tv_name);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			ShopInfo shopInfo = data.get(position);
			holder.textView.setText(shopInfo.getName());
			
			//设置未加载默认图片
			holder.imageView.setDefaultImageResId(R.drawable.default_icon);
			//设置加载异常的图片
			holder.imageView.setErrorImageResId(R.drawable.error);
			
			String url = "http://192.168.30.41:8090/dianpin_03/image/"+shopInfo.getImg();
			holder.imageView.setImageUrl(url, VolleyTool.getInstance(getApplicationContext()).getImageLoader());
			return convertView;
		}
		
		class ViewHolder {
			NetworkImageView imageView;
			TextView textView;
		}
		
	}
}


 
 

你可能感兴趣的:(Android网络操作)