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

先上效果图:

    


先写一个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) {

			}
		};
<span style="white-space:pre">		</span>//如果请求得到的server的data,会进入这个方法
//		Listener<String> listener = new Response.Listener<String>() {
//
//			@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<String> 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<String, String> getHeaders() throws AuthFailureError {
				HashMap<String, String> headers = new HashMap<String, String>();
				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<String>() {

			@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:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="56dp"
    android:minHeight="56dp"
    >

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/image_icon"
        android:layout_width="@dimen/favorites_item_picture_width"
        android:layout_height="@dimen/favorites_item_picture_height"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="5dp"
         />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginLeft="@dimen/messages_list_view_text_margin_left"
        android:layout_toRightOf="@+id/image_icon"
        android:background="@drawable/bg_list_item_divider"
         >

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="10dp"
            android:ellipsize="marquee"
            android:gravity="center_vertical|left"
            android:singleLine="true"
            android:textColor="#000000"
            android:textSize="@dimen/font_size_medium" />
        
        <TextView
            android:id="@+id/info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:layout_below="@id/name"
            android:ellipsize="marquee"
            android:gravity="center_vertical|left"
            android:singleLine="true"
            android:textColor="#000000"
            android:textSize="@dimen/font_size_small" />
    </RelativeLayout>

</RelativeLayout>

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<ShopData> items = new ArrayList<ShopData>();
		
		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下载

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

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