使用Volley来写一个List列表(Valley可以解决很大一部分android请求server的问题)

先上效果图:

    使用Volley来写一个List列表(Valley可以解决很大一部分android请求server的问题)_第1张图片


先写一个Volley的请求的类:

public  void fetchData() {
		String url = "http://2.novelread.sinaapp.com/framework-sae/index.php";
		
//		String body = "";
//		try {
//			mEntity = new StringEntity(body);
//		} catch (UnsupportedEncodingException e1) {
//			e1.printStackTrace();
//		}
		
		//如果发生错误,会进入这个监听
		ErrorListener errorListener = new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError arg0) {

			}
		};
		//如果请求得到的server的data,会进入这个方法
//		Listener listener = new Response.Listener() {
//
//			@Override
//			public void onResponse(String message) {
//				Log.d(TAG, "message ="+message);
//			}
//		};

		RequestQueue requestQueue = Volley.newRequestQueue(mContext);
		StringRequest request = new StringRequest(Request.Method.GET, url, mListener, errorListener) //构造request
		
		{

		    @Override
			protected Response parseNetworkResponse(NetworkResponse response) {
		    	 try {
		             String jsonString = new String(response.data, "UTF-8");
		             return Response.success(jsonString,
		                     HttpHeaderParser.parseCacheHeaders(response));
		         } catch (UnsupportedEncodingException e) {
		             return Response.error(new ParseError(e));
		         } catch (Exception je) {
		             return Response.error(new ParseError(je));
		         }
			}
		    
			@Override
			public Map getHeaders() throws AuthFailureError {
				HashMap headers = new HashMap();
				headers.put("key", "value");
				return headers;
			}

			@Override
			public byte[] getPostBody() throws AuthFailureError {
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				try {
					mEntity.writeTo(outputStream);
				} catch (IOException e) {
					Log.e(TAG, "IOException @ " + getClass().getSimpleName());
				}
				return outputStream.toByteArray();
			}

			@Override
			public String getPostBodyContentType() {
				  return mEntity.getContentType().getValue();
			}

		}//重载的方法体
		;

		requestQueue.add(request);
	}


 
  

在Activity里只要去解析数据然后放到ListView里就可以了

		mListener = new Response.Listener() {

			@Override
			public void onResponse(String message) {
				Log.d(TAG, "message ="+message);
				parseJson(message);
			}
		};
		
		isShowListView(false);
		GetDataViaVolley valley = GetDataViaVolley.getInstance(this);
		valley.setListener(mListener);
		valley.fetchData();
	}
	
	private void parseJson(String content) {
		try {
			JSONArray json = new JSONArray(content);
			String str = "";
			for (int i = 0; i < json.length(); i++) {
				str = (String) json.getString(i);
				JSONArray tempArray = (JSONArray) json.get(i);
				ShopData data = new ShopData();
				data.shopId = tempArray.getString(0);
				data.name = tempArray.getString(1);
				data.url = convert(tempArray.getString(2));
				data.info = tempArray.getString(3);

				mAdapter.items.add(data);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		isShowListView(true);
		mAdapter.notifyDataSetChanged();
	}

	private static String convert(String str) {
		return str.replaceAll("\\\\", "");
	}
	
	private void isShowListView(Boolean flag) {
		mListView.setVisibility(flag?View.VISIBLE:View.GONE);
		loadingLayout.setVisibility(flag?View.GONE:View.VISIBLE);
	}

图片加载用NetWorkImagView来实现,看ListView的item的Layout:



    

    

        
        
        
    


ListView的adapter的实现:

   private void showImageByNetworkImageView(NetworkImageView imageView,String url){  
        RequestQueue requestQueue = Volley.newRequestQueueInDisk(this, "/sdcard/demo/", null);
        ImageLoader imageLoader = new ImageLoader(requestQueue, new BitmapCache());  
        imageView.setTag("url");  
        imageView.setDefaultImageResId(R.drawable.big_head_icon);
        imageView.setImageUrl(url,imageLoader);  
    }  

    
	private class ListAdapter extends BaseAdapter{

		protected List items = new ArrayList();
		
		public ListAdapter(){
			super();
		}
		@Override
		public int getCount() {
			return items.size();
		}

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

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			ShopDataTag tag = new ShopDataTag();//这个目的是重用convertView
			if(convertView == null) {
				convertView = mInflater.inflate(R.layout.listitem, null);
				tag.name = (TextView)convertView.findViewById(R.id.name);
				tag.shopInfo = (TextView)convertView.findViewById(R.id.info);
				tag.icon = (NetworkImageView)convertView.findViewById(R.id.image_icon);
				convertView.setTag(tag);
			}else{
				tag = (ShopDataTag)convertView.getTag();
			}
			
			TextView name = tag.name;
			TextView info = tag.shopInfo;
			NetworkImageView imageView = tag.icon;
			ShopData data = items.get(position);
			name.setText(data.name);
			info.setText(data.info);
			showImageByNetworkImageView(imageView, data.url);
			return convertView;
		}
		
	}
	
	private class ShopDataTag{
		TextView name;
		TextView shopInfo;
		NetworkImageView icon;
	}


代码可以在 http://download.csdn.net/detail/baidu_nod/7606877下载

你可能感兴趣的:(android技术)