【Android】Handler的应用(三):从服务器端分页加载更新ListView

在前面两节中,我们了解了如何从服务器中加载JSON数据。

现在,我们将把服务器中的JSON数据加载更新到ListView。

并且,结合之前博文的  “动态追加分页ListView数据”的相关知识,实现将服务器中的分页JSON数据,填充到ListView中。


回顾

以BaseAdapter做适配器的ListView:http://blog.csdn.net/jueblog/article/details/12114513

ListView内数据的动态追加:http://blog.csdn.net/jueblog/article/details/12148259


Activity的实现

package com.app.myhandler;



import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;



import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.view.ContextMenu;

import android.view.ContextMenu.ContextMenuInfo;

import android.view.LayoutInflater;

import android.view.MenuItem;

import android.view.View;

import android.widget.AdapterView;

import android.widget.AdapterView.AdapterContextMenuInfo;

import android.widget.ListView;

import android.widget.TextView;

import android.widget.Toast;



import com.app.adapter.MyWeixinJSON;

import com.app.util.MyApplication;

import com.app.util.MyThread;



/**

 * 点击 追加数据的ListView

 * @author 402-9

 */

public class ListViewPage extends Activity {

	private ListView lv;

	private MyWeixinJSON mJson;

	private JSONArray mData = new JSONArray();// JSON数据源

	private View view_page_footer;// 底部视图

	private int page = 1;// 加载页码

	private int totalPage;// 总数据

	private String url = new String("http://192.168.8.4/wt_guang.php?frm=3g&cid=100");

	private TextView text_page;

	

	private Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			try {

				String result = msg.obj.toString();

				JSONObject object = new JSONObject(result);

				totalPage = (Integer) object.get("totalPage");

				if(mJson==null) {

					mData = (JSONArray) object.get("items");

					mJson = new MyWeixinJSON(mData, ListViewPage.this);

					lv.setAdapter(mJson);//为ListView绑定适配器	

				} else {

					mData = MyApplication.joinJSONArray(mData, (JSONArray) object.get("items"));

					mJson.setList(mData);

					mJson.notifyDataSetChanged();

				}	

				text_page.setText("下一页");

			} catch (JSONException e) {

				// TODO Auto-generated catch block

				e.printStackTrace();

			}

		};

	};



	@Override

	protected void onCreate(Bundle savedInstanceState) {

		// TODO Auto-generated method stub

		super.onCreate(savedInstanceState);

		setContentView(R.layout.weixin);

		lv = (ListView) findViewById(R.id.lv);



		new MyThread(handler, url.toString(), 1).start();

		

		view_page_footer = LayoutInflater.from(this).inflate(R.layout.view_page_footer, null);

		lv.addFooterView(view_page_footer);// 添加底部视图

		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override

			public void onItemClick(AdapterView<?> parent, View view,

					int position, long id) {

				// TODO Auto-generated method stub

				try {

					JSONObject jsonObject = (JSONObject) mData.get(position);

					Toast.makeText(ListViewPage.this,

							jsonObject.getString("title"), Toast.LENGTH_SHORT)

							.show();

				} catch (JSONException e) {

					// TODO Auto-generated catch block

					e.printStackTrace();

				}

			}

		});



		text_page = (TextView) view_page_footer.findViewById(R.id.text_page);

		text_page.setOnClickListener(new View.OnClickListener() {

			// 点击按钮 追加数据 并通知适配器

			@Override

			public void onClick(View v) {

				// TODO Auto-generated method stub

				page++;

				if(page<=totalPage) {			

					text_page.setText("正在加载中...");

					new MyThread(handler, url+"&p="+page, 1).start();				

				} else {

					text_page.setText("已是最末页...");

					text_page.setEnabled(false);

				}

			}

		});

	}

}

mData = MyApplication.joinJSONArray(mData, (JSONArray) object.get("items"));
所调用的方法为 http://blog.csdn.net/jueblog/article/details/12622423中提供的方法。

适配器的修改

package com.app.adapter;



import org.json.JSONArray;

import org.json.JSONObject;



import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.ImageView;

import android.widget.TextView;



import com.app.myhandler.R;



public class MyWeixinJSON extends BaseAdapter {

	private LayoutInflater mInflater;// 动态布局映射

	private JSONArray list;

	private Context context;

//	private int i = 0;



	public void setList(JSONArray list) {

		this.list = list;

	}



	public MyWeixinJSON(JSONArray list, Context context) {

		this.list = list;

		this.context = context;

		this.mInflater = LayoutInflater.from(context);

	}



	@Override

	public int getCount() {

		// TODO Auto-generated method stub

		return list.length();

	}



	@Override

	public Object getItem(int position) {

		// TODO Auto-generated method stub

		return null;

	}



	@Override

	public long getItemId(int position) {

		// TODO Auto-generated method stub

		return 0;

	}



	@Override

	public View getView(int position, View convertView, ViewGroup parent) {

		// TODO Auto-generated method stub

		// System.out.println("正在渲染第"+position+"行  +++  "+ i++);

		OneView oneView;

		if (convertView == null) {

			convertView = mInflater.inflate(R.layout.item_weixin, null);// 根据布局文件实例化view

			oneView = new OneView();

			oneView.title = (TextView) convertView.findViewById(R.id.title);// 找某个控件

			oneView.time = (TextView) convertView.findViewById(R.id.time);

			oneView.info = (TextView) convertView.findViewById(R.id.info);

			oneView.img = (ImageView) convertView.findViewById(R.id.img);

			convertView.setTag(oneView);// 把View和某个对象关联起来

		} else {

			oneView = (OneView) convertView.getTag();

		}

		JSONObject jObject = null;

		try {

			jObject = list.getJSONObject(position);// 根据position获取集合类中某行数据

			oneView.title.setText(jObject.get("itemID").toString());// 给该控件设置数据(数据从集合类中来)

			oneView.time.setText(jObject.get("price").toString());

			oneView.info.setText(jObject.get("title").toString());

			oneView.img.setBackgroundResource(R.drawable.special_spring_head2);

			// oneView.img.setImageDrawable(Drawable.createFromStream(new

			// URI(jObject.getString("pic_url"))., "src"));

		} catch (Exception e) {

			// TODO: handle exception

		}

		return convertView;

	}



	/** 把每行布局文件的各个控件包装成一个对象 */

	private class OneView {

		TextView title;

		TextView time;

		TextView info;

		ImageView img;

	}

}


JSON数据

最后 瞄一眼服务器上的JSON数据:
{

    "totalCount": 9,

    "totalPage": 2,

    "items": [

        {

            "itemID": "13889239752",

            "title": "PEACE DOVE 正品* 真兔毛 范儿厚毛衣开衫 清库价",

            "pic_url": "http://img01.taobaocdn.com/bao/uploaded/i5/T1ELuGXj0yXXbAjkA._083138.jpg",

            "click_url": "http://item.taobao.com/item.htm?id=13889239752",

            "price": "98.00",

            "promotion_price": "0.00",

            "liked": "0"

        },

        {

            "itemID": "13357878044",

            "title": "现货 呛口小辣椒11月29日香港行snidel 翻领双排扣毛呢大衣外套",

            "pic_url": "http://img03.taobaocdn.com/bao/uploaded/i3/T1KTWDXipfXXXmSFDX_113804.jpg",

            "click_url": "http://item.taobao.com/item.htm?id=13357878044",

            "price": "278.00",

            "promotion_price": "0.00",

            "liked": "0"

        },

        {

            "itemID": "12740033159",

            "title": "2011新款呛口小辣椒子萱王翔貉子毛毛领军绿色工装棉服棉衣大衣",

            "pic_url": "http://img01.taobaocdn.com/bao/uploaded/i1/T1WiCoXi4BXXad.Qs9_073952.jpg",

            "click_url": "http://item.taobao.com/item.htm?id=12740033159",

            "price": "628.00",

            "promotion_price": "0.00",

            "liked": "0"

        },

        {

            "itemID": "8603809978",

            "title": "圣诞款大衣 三色入",

            "pic_url": "http://img01.taobaocdn.com/bao/uploaded/i1/T1GWXTXhhxXXaMGqo3_045745.jpg",

            "click_url": "http://s.click.taobao.com/t_8?e=7HZ6jHSTZTlU5Xur%2B%2F50d2poSR5Ba0A%2Fi8tpiW6m04z%2BWKzb6yELcZsJq6zxF7EMTqmpst%2FNOGepsZQvjjXKR0huW7F8S1whVzYKzICAu1lT&p=mm_10009952_0_0",

            "price": "165.00",

            "promotion_price": "0.00",

            "liked": "0"

        },

        {

            "itemID": "10629952619",

            "title": "裁诺 春装新款2012女装 韩版带帽中长款加厚卫衣 女 秋冬外套大码",

            "pic_url": "http://img01.taobaocdn.com/bao/uploaded/i1/T1PASfXfpoXXc.O0vb_093452.jpg",

            "click_url": "http://item.taobao.com/item.htm?id=10629952619",

            "price": "158.00",

            "promotion_price": "0.00",

            "liked": "0"

        },

        {

            "itemID": "9158721999",

            "title": "清仓包邮 出口欧美大码超酷水洗打磨斜开襟修身加厚抓绒卫衣外套",

            "pic_url": "http://img03.taobaocdn.com/bao/uploaded/i3/T12t5KXXJqXXbjSw.8_100610.jpg",

            "click_url": "http://s.click.taobao.com/t_8?e=7HZ6jHSTZPhaK%2FmBeumaH2YuQWkORNRTfXSCf08v9iowvo%2F0Akhswsb9gfNlScFQL%2Bc%2Bp%2BFUQiV5QW7qQyiq%2BJQ4CS399exvrZIKVVH3ZZNULw%3D%3D&p=mm_10009952_0_0",

            "price": "398.00",

            "promotion_price": "0.00",

            "liked": "0"

        }

    ]

}

效果图

由于服务器JSON数据是比较随意找的,所以内容不是很适合“微信”屏幕。
不要在意这些细节、、、

程序执行的第一页:
【Android】Handler的应用(三):从服务器端分页加载更新ListView

点击下一页,将会动态追加第二页的数据
【Android】Handler的应用(三):从服务器端分页加载更新ListView

由于服务器中只有两页数据,所以当再次点击“下一页”时,会显示“已是最末页”
【Android】Handler的应用(三):从服务器端分页加载更新ListView

 

你可能感兴趣的:(ListView)