客户端访问服务器批量显示数据

批量获取服务器的信息,显示在本地  不向服务器发信息直接获取

定义一个类,访问服务器并显示在这个页面显示在一个简单的ListView里面

访问服务器的类

定义初始化

//显示信息的ListView	
private ListView lv_leave;
//填充访问服务器类的Adapter	
LeaveInfoAdapter lva;
ArrayList<LeaveInfo> list = new ArrayList<LeaveInfo>();

在onCreate方法里面开始访问

                setContentView(R.layout.leave_show);
		lv_leave = (ListView) findViewById(R.id.leave_show_list);

		try {
			 
                       //将访问服务器获取到的值都保存在list里面
			list = JSONUtil.postRequest("http://172.16.10.131:8080/workflow/workapprove!phoneFindStatus02.action");

              //然后将这个list传给填充访问服务器类的Adapter
			lva = new LeaveInfoAdapter(list, this);

//将Adapter赋值给ListView
        	         lv_leave.setAdapter(lva);
			 
		} catch (Exception e) {
			System.out.println("网络异常");
			e.printStackTrace();
		}

JsonUtil解析将获取到的值保存在一个list里面并传到访问服务器类里面定义的list里面

public class JSONUtil {
	private static final String TAG = "JSONUtil";

	/**
	 * 获取json内容
	 * 
	 * @param url
	 * @return JSONArray
	 * @throws JSONException
	 * @throws ConnectionException
	 */
	public static JSONObject getJSON(String url) throws JSONException,
			Exception {

		return new JSONObject(getRequest(url));
	}

	/**
	 * 向api发送get请求,返回从后台取得的信息。
	 * 
	 * @param url
	 * @return String
	 */
	protected static String getRequest(String url) throws Exception {
		return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
	}

	protected static ArrayList<LeaveInfo> postRequest(String url)
			throws Exception {
		return postRequest(url, new DefaultHttpClient());
	}

	/**
	 * 向api发送get请求,返回从后台取得的信息。
	 * 
	 * @param url
	 * @param client
	 * @return String
	 */
	protected static String getRequest(String url, DefaultHttpClient client)
			throws Exception {
		String result = null;
		int statusCode = 0;
		HttpGet getMethod = new HttpGet(url);
		Log.d(TAG, "do the getRequest,url=" + url + "");
		try {
			// getMethod.setHeader("User-Agent", USER_AGENT);
			HttpResponse httpResponse = client.execute(getMethod);
			 statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.d(TAG, "statuscode = " + statusCode);
		 
			result = retrieveInputStream(httpResponse.getEntity());
			 
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			throw new Exception(e);
		} finally {
			getMethod.abort();
		}
		return result;
	}

	protected static ArrayList<LeaveInfo> postRequest(String url,
			DefaultHttpClient client) throws Exception {
		String result = null;
		int statusCode = 0;
		 ArrayList<LeaveInfo> list = new ArrayList<LeaveInfo>();
		HttpPost getMethod = new HttpPost(url);
		Log.d(TAG, "do the postRequest,url=" + url + "");
		try {
			// getMethod.setHeader("User-Agent", USER_AGENT);
			HttpResponse httpResponse = client.execute(getMethod);
			// statusCode == 200 正常
			statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.d(TAG, "statuscode = " + statusCode);
			// 处理返回的httpResponse信息
			if (statusCode == 200) {

				HttpEntity entity = httpResponse.getEntity();
				result = retrieveInputStream(entity);
				
				 
				JSONArray jsonArray = new JSONArray(result );
				System.out.println(jsonArray);
				for (int i = 0, size = jsonArray.length(); i < size; i++) {
					LeaveInfo bean = new LeaveInfo();
					JSONObject jsonObject = jsonArray.getJSONObject(i);

					bean.setId(jsonObject.getInt("id"));
					bean.setApplyname(jsonObject.getString("applyname"));
					bean.setApplytime(jsonObject.getString("applytime"));
					bean.setReason(jsonObject.getString("reason"));
					bean.setStatus(jsonObject.getString("status"));
					list.add(bean);
				}
				 
				
			}

		} catch (Exception e) {
			// Log.e(TAG, e.getMessage());
			throw new Exception(e);
		} finally {
			// getMethod.abort();
		}
		return list;
	}

	/**
	 * 处理httpResponse信息,返回String
	 * 
	 * @param httpEntity
	 * @return String
	 */
	protected static String retrieveInputStream(HttpEntity httpEntity) {

		int length = (int) httpEntity.getContentLength();
		// the number of bytes of the content, or a negative number if unknown.
		// If the content length is known but exceeds Long.MAX_VALUE, a negative
		// number is returned.
		// length==-1,下面这句报错,println needs a message
		if (length < 0)
			length = 10000;
		StringBuffer stringBuffer = new StringBuffer(length);
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(
					httpEntity.getContent(), "UTF-8");
			char buffer[] = new char[length];
			int count;
			while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
				stringBuffer.append(buffer, 0, count);
			}
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, e.getMessage());
		} catch (IllegalStateException e) {
			Log.e(TAG, e.getMessage());
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
		}
		System.out.println("resulte:" + stringBuffer.toString());
		return stringBuffer.toString();
	}

}

 填充访问服务器类的Adapter

扫描二维码关注公众号,回复: 722322 查看本文章
public class LeaveInfoAdapter extends BaseAdapter {
	List<LeaveInfo>  list;
	Context mcontext;

	public LeaveInfoAdapter(List<LeaveInfo> list, Context context) {

		this. list = list;
		this.mcontext = context;
	}

	public void setResult(List<LeaveInfo> list, Context context) {
		this. list = list;
		this.mcontext = context;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return  list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = LayoutInflater.from(mcontext);
			convertView = inflater.inflate(R.layout.leave, null);
		}
		TextView tv_name = (TextView) convertView.findViewById(R.id.leave_name);
		tv_name.setText( "姓名:"+list.get(position).getApplyname());
		TextView tv_time = (TextView) convertView.findViewById(R.id.leave_time);
		tv_time.setText("请假时间"+ list.get(position).getApplytime());
		TextView tv_reason = (TextView) convertView
				.findViewById(R.id.leave_reason);
		tv_reason.setText( "请假原因"+list.get(position).getReason());
		TextView tv_status = (TextView) convertView
				.findViewById(R.id.leave_status);
		tv_status.setText( "状态:"+list.get(position).getStatus());

		return convertView;
	}

}

LeaveInfo 实体对象

public class LeaveInfo {

private int id ;
private String applyname  ;
private String applytime  ;
private String reason ;
private String status  ;
然后是Getters跟Setters方法
有参构造方法跟无参构造方法

}

 然后就是定义一个leave_show.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    
<ListView 
    android:id="@+id/leave_show_list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"></ListView>
</LinearLayout>

定义一个填充Adapter的XMl        leave.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/leave_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

    <TextView
        android:id="@+id/leave_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/leave_reason"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
          />

    <TextView
        android:id="@+id/leave_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />
 
</LinearLayout>

以上代码就是android客户端直接访问服务器获取数据并显示在本地的ListView的实例

猜你喜欢

转载自m-wen997721750.iteye.com/blog/1775825