使用AsyncTask请求服务器并在客户端图文并排

最近学习android使用到了asyncTask来请求服务器并在客户端图文并排,服务器返回结果为json,在客户端用listView显示。为了模仿请求服务器的效果,在tomcat的ROOT目录下面建立一个json格式的文件,json格式如下:

	{
    users:[
			{name:"张三",title:"开发人员",face:"one.jpg"},
			{name:"李四",title:"管理人员",face:"two.jpg"}
		]
	}
本着OO的思想,就在客户端建立一个一个实体对象,省去get、set 构造

public class User {
	private String name;
	private String title;
	private String face;
}
在main.xml中编写一个显示所有数据的listView

<ListView
        android:id="@+id/list1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>
然后在MainActivity中编写业务代码

public class MainActivity extends Activity {
	String path = "http://192.168.4.112:8080/phototext/json1.html";
	private ListView listView;
	private ProgressDialog dialog;
	private PhototextAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		dialog = new ProgressDialog(MainActivity.this);
		listView = (ListView) findViewById(R.id.list1);

		new PhotoTextTask().execute(path);
	}

	class PhotoTextTask extends AsyncTask<String, Void, List<User>> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.setTitle("提示信息");
			dialog.setMessage("正在下载,请稍候...");
			dialog.show();
		}

		@Override
		protected List<User> doInBackground(String... params) {
			List<User> list = new ArrayList<User>();
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(params[0]);
			try {
				HttpResponse httpResponse = httpClient.execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					//发送请求,并设置编码
					String json = EntityUtils
							.toString(httpResponse.getEntity(),"UTF-8");
					JSONObject jsonObj = new JSONObject(json);
					//解析JSON
					JSONArray jsonArray = jsonObj.getJSONArray("users");
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject obj = jsonArray.getJSONObject(i);
						User user = new User();
						user.setFace(obj.getString("face"));
						user.setName(obj.getString("name"));
						user.setTitle(obj.getString("title"));
						list.add(user);
					}
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<User> result) {
			super.onPostExecute(result);
			dialog.dismiss();
			if(result.size()<0){
				return;
			}
			adapter = new PhototextAdapter(result, MainActivity.this);
			listView.setAdapter(adapter);
		}
	}

	class PhototextAdapter extends BaseAdapter {
		private Context context;
		private List<User> list;
		private LayoutInflater inflater;

		public PhototextAdapter(List<User> list, Context context) {
			super();
			this.list = list;
			this.context = context;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {

			return list.size();
		}

		@Override
		public Object getItem(int position) {

			return list.get(position);
		}

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = null;
			if (convertView != view) {
				view = convertView;
			} else {
				view = inflater.inflate(R.layout.phototext_item, null);
			}
			final ImageView iv_photo=(ImageView)view.findViewById(R.id.face);
			TextView tvUserName = (TextView) view.findViewById(R.id.tvUserName);
			TextView tvHeadShip = (TextView) view.findViewById(R.id.tvHeadShip);
			//图片地址
			String face_path="http://192.168.4.112:8080/phototext/"+list.get(position).getFace();
			
			DownloadFace face=new DownloadFace(face_path);
			//使用回调的方式获得数据
			face.loadImageForUrl(new downloadFaceCallBack() {
				
				@Override
				public void setDrawable(Drawable drawable) {
					iv_photo.setImageDrawable(drawable);
				}
			});
			tvUserName.setText(list.get(position).getName());
			tvHeadShip.setText(list.get(position).getTitle());
			
			return view;
		}
	}
}
在MainActivty中使用了适配器来加载更多的数据,使用到了一个xml文件,这个xml文件主要是来显示更多的图文项,布局如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/face"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:contentDescription="@string/txt_img1"
        android:src="@drawable/lie" />

    <TextView
        android:id="@+id/tvUserName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/face"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tvHeadShip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tvUserName"
        android:layout_toRightOf="@id/face"
        android:textSize="16sp" />

</RelativeLayout>
另外还在MainActivity中还使用到了一个回调函数:DownloadFace,这个类的主要代码如下:

public class DownloadFace {
	String url;

	public DownloadFace(String url) {
		super();
		this.url = url;
	}
	public void loadImageForUrl(final downloadFaceCallBack faceCallBack){
		final Handler handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				Drawable drawable=(Drawable) msg.obj;
				faceCallBack.setDrawable(drawable);
			};
		};
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Drawable drawable=Drawable.createFromStream(new URL(url).openStream(),"");
					Message message=Message.obtain();
					message.obj=drawable;
					handler.sendMessage(message);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
		
	}
	public interface downloadFaceCallBack{
		public void setDrawable(Drawable drawable);
	}
}

效果图如下:








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值