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

1.首先搭建服务器端。

 使用MyEclipse开发工具

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        ArrayList food = new ArrayList();
        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 map = new HashMap();
        
        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与服务器端数据交互_第1张图片

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

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

public class MainActivity extends Activity {

    private ListView lv;
    
    private List  data = new ArrayList();
    
    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>{
        @Override
        protected void onPreExecute() {
            
            pd.setMessage("Loading...");
            
        }

        

        @Override
        protected Map 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 map =  parseJson(result);
                    return map;
                    
                }
            
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
            
            return null;
        }
        
        
        @Override
        protected void onPostExecute(Map result) {
                
            pd.dismiss();
            isNextPage =  (Boolean) result.get("isNextPage");
            data.addAll(  (List) result.get("foodList")  );
            mAdapter.notifyDataSetChanged();
            
            for(int i = 0;i){
                
                Food f = data.get(i);
                
                new MyImgTask().execute(f);
            
        }    
    }
    
    
    private Map parseJson(String json) throws Exception{
        
        Map result = new HashMap();
        List lists = new ArrayList();
        JSONObject  bigObj = new JSONObject(json);
        result.put("isNextPage",  bigObj.getBoolean("isNextPage"));
        JSONArray array = bigObj.getJSONArray("foodList");
        Food  f = null;
        for(int i =0 ;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{

        @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  data ;
    
    
    public MyAdapter(Context context, List 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与服务器端数据交互_第2张图片

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

 

转载于:https://www.cnblogs.com/mengxiao/p/6872385.html

你可能感兴趣的:(移动开发,json,开发工具)