尝试利用android手机客户端查询web端数据
这里发图片好像不太好发,更多内容请访问我的博客文章的连接地址:http://www.
读取json数据并绑定数据源的代码:
package net.dofind.lifeservice.activity;
import
import
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.dofind.lifeservice.R;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class UserActivity extends Activity {
private static final String URL = "http://system.
private TextView userList;
private ListView mListView = null;
private List<Map<String, String>> listData=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
initJsonData(); //初始化json数据
bundleData(); //绑定json数据至dataview
}
/**
* 初始化界面
*/
public void initJsonData(){
HttpClient client = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
userList = (TextView) findViewById(R.id.userList);
try {
HttpGet get = new HttpGet(URL);
get.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
HttpResponse response = client.execute(get);
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
for (String s = reader.readLine(); s != null; s = reader
.readLine()) {
builder.append(s);
}
listData=new ArrayList<Map<String,String>>();
JSONArray jsonArray = new JSONArray(builder.toString());
Map<String,String> headMap=new HashMap<String,String>();
headMap.put("username", "用户名");
headMap.put("password", "密 码");
headMap.put("createDate", "创建时间");
listData.add(headMap);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
Map<String,String> map=new HashMap<String,String>();
map.put("username", item.getString("username"));
map.put("password", item.getString("password"));
//将时间戳传换成重用的date字符串
SimpleDateFormat format=new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
long dateMin=Long.parseLong(item.getString("createDate"));
String createDate=format.format(dateMin);
map.put("createDate", createDate);
listData.add(map);
}
bundleData(); //绑定Item数据源
} catch (Exception e) {
e.printStackTrace();
userList.setText("数据加载异常!");
}
}
/**
* 绑定Adapter数据源
*/
public void bundleData() {
SimpleAdapter adapter = new SimpleAdapter(this, listData,
R.layout.user_list_item, new String[] { "username", "password", "createDate" },
new int[] { R.id.user_username, R.id.user_password, R.id.user_createDate });
mListView = (ListView) this.findViewById(R.id.userListView);
mListView.setAdapter(adapter);
}
}