Android-Volley网络通信框架(volley 例子:电影列表)

1.回顾:

    上篇学习了 自定义 GsonRequest 的实现,直接将 Json字符串 转换为 Model对象

2.重点

   (1)Adapter 的实现 适配 到 listview  : 涉及到图片请求(ImageLoader 实现)

   (2)使用JsonObjectRequest 请求数据 

3.效果展示

    

4.实现

   1)新建 MovieActivity 实现布局 

  

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="#abcdef"
        android:gravity="center"
        android:text="电影列表"
        android:textColor="#fff"
        android:textSize="20dp" />

    <ListView
        android:id="@+id/move_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1" >
    </ListView>

</RelativeLayout>

   2)实现 MovieAdapter  继承自 BasicAdapter

      其中的 BitmapCache 的实现,见文章:Volley网络通信框(ImageRequest,ImageLoader,NetWorkImageView) 

  实现的图片缓存;HttpPath是 网络请求地址;

/**
	 * 继承baseAdapter 准备适配给listview
	 * @author yuan
	 * 
	 */
	class MovieListAdapter extends BaseAdapter{

		List<shared> mlist=null;
		
		public MovieListAdapter(List<shared> list) {
			//初始化 List<shared> 列表
			this.mlist=list;
		}
		
		@Override
		public int getCount() {
			return mlist.size();
		}

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

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			//初始化 控件
			convertView=View.inflate(getApplicationContext(), R.layout.list_item,null);
			
			ImageView imageView=(ImageView)convertView.findViewById(R.id.img_movie);
			TextView movie_name=(TextView)convertView.findViewById(R.id.movie_name);
			TextView movie_totol=(TextView)convertView.findViewById(R.id.movie_totol);
		    
			//设置 背景为 灰色
			if(position%2==0){
			  convertView.setBackgroundColor(Color.GRAY);
			}
			
			//设置参数
			shared s=mlist.get(position);
			movie_name.setText(s.getName());
			movie_totol.setText(s.getTotol());
			//设置图片
			imageLoader_cache(imageView,s.getPic());
			
			return convertView;
	  }
		
		//加载图片
		private void imageLoader_cache(ImageView imageView,String pic){
			
			//设置 图片缓存 :体现 imageLoader的优势
	         //使用 LruBitmap + ImageCache 实现 
			//实例化对象
			ImageLoader imageLoader=new ImageLoader(volleyApplication.getQueue(),new BitmapCache());
			// 图片监听 (默认图片,错误图片) 和 imageView
			ImageListener imageListener=ImageLoader.getImageListener(imageView,R.drawable.ic_launcher,R.drawable.ic_launcher);
			
			//加载图片 后面可以设置 图片的大小缩放
			imageLoader.get(HttpPath.getBasicPath()+"/"+pic,imageListener,0,0);
			
		}
		
	}


              通过BasicAdapter实现,布局为自定义布局;在 layout 添加 list_item.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_marginTop="5dp"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:orientation="horizontal" 
    android:background="#cccccc"
    
    >

    <ImageView
        android:id="@+id/img_movie"
        android:layout_width="120dp"
        android:layout_height="80dp"
        android:src="@drawable/ic_launcher"
         />

    <LinearLayout 
     android:orientation="vertical"
     android:layout_width="wrap_content"
     android:layout_height="80dp"
     >
      <TextView
         android:id="@+id/movie_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="movie_name"
       android:textColor="#00ff00"
        />
     
      <TextView
        android:id="@+id/movie_totol"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="movie_totol"
        android:textColor="#fff"
        />
     
 </LinearLayout>


</LinearLayout>

   3)实现 getMovieList 方法 通过JsonObjectRequest 实现

       这样实现起来更方便一些,其中 返回的Json对象,先进行数据解析,返回为list集合,后适配到listview里!

   这样就不用考虑 图片缓存和内存溢出了!

	//请求信息
	
	private void getMovieList(){
		
		String url=HttpPath.getSharedAll();
		Show(url);
		JsonObjectRequest objectRequest=new JsonObjectRequest(Method.POST,url
				,null,new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						// 设置参数
						List<shared> list=new ArrayList<shared>();
						String str="网络错误";
						try {
							if(response.getString("msg").equals("success")&&response.getInt("code")==1){
								
								//json解析 为 List<shared> 
								JSONArray array=new JSONArray(response.getString("data"));
								for(int i=0;i<array.length();i++){
									JSONObject object=(JSONObject) array.get(i);
									shared s=new shared();
									s.setId(object.getInt("id"));
									s.setName(object.getString("name"));
									s.setPic(object.getString("pic"));
									s.setTotol(object.getString("totol"));
									list.add(s);
								}
								if(list.size()>0){
									//解析完毕 ,适配 listview
									MovieListAdapter adapter=new MovieListAdapter(list);
									move_list.setAdapter(adapter);
									
								}else{
									str="没有解析出来"+response.toString();
									Show(str);
								}
								
							}else{
								Show(response.getString("msg"));
							}
						} catch (JSONException e) {
							// 发生异常
							Show(e.getMessage());
						}
						
					}
			

				},new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						// 失败
						Show(error.getMessage());
					}
				});
		
		//一定添加到队列中
		objectRequest.setTag("movieList");
		volleyApplication.getQueue().add(objectRequest);
		
	}
	
	/**
	 * toast 
	 * @param msg
	 */
	private void Show(String msg){
		Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
	}
	


   4)总结

    通过Volley 来实现 网络的请求 ,使用起来很方便;要注意的是,在使用的时候,需要实现 RequestQueue 请求队列的实现;放在请求队列的去请求数据;


5.demo  免积分下载

http://download.csdn.net/detail/lablenet/9029321






评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值