Android开发学习——android与服务器端数据交互

1.首先搭建服务器端。

使用MyEclipse开发工具

public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException { ArrayList<Food> food = new ArrayList<Food>();
Gson g = new Gson(); Food f1 = new Food(1,"1111","1111","/cinema_1.jpg");
Food f2 = new Food(2,"2222","22222","/cinema_2.jpg");
Food f3 = new Food(3,"3333","33333","/food_1.jpg");
Food f4 = new Food(4,"44444","4444","/food_2.jpg");
Food f5 = new Food(5,"55555","5555","/hotel_1.jpg"); food.add(f1);
food.add(f2);
food.add(f3);
food.add(f4);
food.add(f5); boolean isNextPage = false;
Map<String,Object> map = new HashMap<String,Object>(); map.put("foodList", food);
map.put("isNextPage", isNextPage); resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter();
out.print(g.toJson(map));
out.close();
}
}

上述代码所需的Food实体如下:

public class Food implements Serializable{
private int id; private String name; private String desc; private String imgPath; public Food(int id, String name, String desc, String imgPath) {
super();
this.id = id;
this.name = name;
this.desc = desc;
this.imgPath = imgPath;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getDesc() {
return desc;
} public void setDesc(String desc) {
this.desc = desc;
} public String getImgPath() {
return imgPath;
} public void setImgPath(String imgPath) {
this.imgPath = imgPath;
} }

我们在浏览器中访问

Android开发学习——android与服务器端数据交互

可以获取到结果,说明服务器端是正常的。

2.服务器端搭建好了之后,我们搭建android端

public class MainActivity extends Activity {

    private ListView lv;

    private List<Food>  data = new ArrayList<Food>();

    private MyAdapter mAdapter;

    private ProgressDialog  pd;

    private boolean isNextPage;

    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.lv); pd = new ProgressDialog(this); mAdapter = new MyAdapter(this, data); lv.setAdapter(mAdapter); new MyFoodTask().execute(); } private class MyFoodTask extends AsyncTask<String, Void, Map<String,Object>>{
@Override
protected void onPreExecute() { pd.setMessage("Loading..."); } @Override
protected Map<String, Object> doInBackground(String... params) { String path = "http://10.0.2.2:8080/TestWeb/bbb";
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path); try {
HttpResponse resp = client.execute(get);
if(resp.getStatusLine().getStatusCode()==200){ HttpEntity entity = resp.getEntity();
String result = EntityUtils.toString(entity);
Log.i("111", "result="+result);
Map<String,Object> map = parseJson(result);
return map; } } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
} @Override
protected void onPostExecute(Map<String, Object> result) { pd.dismiss();
isNextPage = (Boolean) result.get("isNextPage");
data.addAll( (List<Food>) result.get("foodList") );
mAdapter.notifyDataSetChanged(); for(int i = 0;i<data.size();i++){ Food f = data.get(i); new MyImgTask().execute(f); }
} private Map<String,Object> parseJson(String json) throws Exception{ Map<String ,Object> result = new HashMap<String,Object>();
List<Food> lists = new ArrayList<Food>();
JSONObject bigObj = new JSONObject(json);
result.put("isNextPage", bigObj.getBoolean("isNextPage"));
JSONArray array = bigObj.getJSONArray("foodList");
Food f = null;
for(int i =0 ;i<array.length();i++){
f = new Food();
JSONObject smallObj = array.getJSONObject(i); f.setId( smallObj.getInt("id") );
f.setName( smallObj.getString("name") );
f.setDesc(smallObj.getString("desc"));
f.setImgPath( smallObj.getString("imgPath") );
lists.add(f);
}
result.put("foodList", lists);
return result; } private class MyImgTask extends AsyncTask<Food, Void, Food>{ @Override
protected Food doInBackground(Food... params) { Food f = params[0];
String imgPath = "http://10.0.2.2:8080/TestWeb"+f.getImgPath(); HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(imgPath);
try {
HttpResponse resp = client.execute(get);
if(resp.getStatusLine().getStatusCode()==200){ HttpEntity entity = resp.getEntity();
byte img [] = EntityUtils.toByteArray(entity);
f.setImgData(img);
} } catch (Exception e) {
e.printStackTrace();
}
return f;
} @Override
protected void onPostExecute(Food result) {
mAdapter.notifyDataSetChanged();
}
}
}
}

所需的Food实体:

public class Food implements Serializable{

    private int id;

    private String name;

    private String desc;

    private String imgPath;

    private byte imgData [];

    public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getDesc() {
return desc;
} public void setDesc(String desc) {
this.desc = desc;
} public String getImgPath() {
return imgPath;
} public void setImgPath(String imgPath) {
this.imgPath = imgPath;
} public byte[] getImgData() {
return imgData;
} public void setImgData(byte[] imgData) {
this.imgData = imgData;
}
}

所需的适配器:

public class MyAdapter  extends BaseAdapter{

    private Context context;

    private List<Food>  data ;

    public MyAdapter(Context context, List<Food> data) {
this.context = context;
this.data = data;
} @Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
} @Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.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){ convertView = LayoutInflater.from(context).inflate(R.layout.item, null); }
ImageView iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
TextView tv_name = (TextView) convertView.findViewById(R.id.tv_name);
TextView tv_desc = (TextView) convertView.findViewById(R.id.tv_desc); Food food = data.get(position); if(food.getImgData()==null){
iv_img.setImageResource(R.drawable.cinema_1);
}else{
byte [] imgData = food.getImgData();
Bitmap bm = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
iv_img.setImageBitmap(bm);
} tv_name.setText( food.getName());
tv_desc.setText( food.getDesc()); return convertView;
} }

我们启动模拟器,得到运行结果:

Android开发学习——android与服务器端数据交互

有兴趣的同学, 可以尝试自己做一下。

上一篇:Android开发学习——Android项目的目录结构


下一篇:HDFS文件操作(命令行)