hyljava

利用AsyncHttpClient与服务器端传输数据

创建一个显示的界面xml
 <ListView
        android:id="@+id/lv_show_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp" >
    </ListView>

再创建一个item.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="vertical" >
   
 <TextView
     android:layout_width="250dip"
     android:layout_height="wrap_content"
     android:id="@+id/title"
    
    
     />
 <TextView
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:id="@+id/timelength"
    
    
     />
</LinearLayout>


导入AsyncHttpClient需要的类

之后


  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_show_list_activy);
  lv_show_view = (ListView) findViewById(R.id.lv_show_view);


   AsyncHttpClient client=new  AsyncHttpClient();
  
   String  url = "http://192.168.1.100:8080/videogetxml/GetParamServlet?userName="
     + "测试方法";
   client.get(url, new AsyncHttpResponseHandler() {
   
  
   public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
     List<Video> list=new ArrayList<Video>();
    try {
     Toast.makeText(ShowListActivy.this,statusCode+"", 1).show();
     
     String json = new String(responseBody);
      JSONArray array = new JSONArray(json);
     for(int i=0 ; i < array.length() ; i++){
      JSONObject item= array.getJSONObject(i);
     
      String id = item.getString("id");
      String title = item.getString("title");
      String timelength = item.getString("time");
      Log.e("jsonget", id+title+timelength);
      list.add(new Video( id, title, Integer.parseInt(timelength)));
     }
     List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
     for (Video v : list) {
      Map<String, Object> it = new HashMap<String, Object>();
      it.put("id", v.getId());
      it.put("title", v.getTitle());
      it.put("timelength", v.getTime());
      data.add(it);
     }
     SimpleAdapter adapter = new SimpleAdapter(ShowListActivy.this, data,R.layout.item, new String[] { "title", "timelength" },new int[] { R.id.title, R.id.timelength });
     lv_show_view.setAdapter(adapter);

     
     
     
    } catch ( Exception e) {
      Log.e("MainActivity", e.toString());
     
    }     
    
    
   }
   
  
   public void onFailure(int statusCode, Header[] headers,
     byte[] responseBody, Throwable error) {
    Toast.makeText(ShowListActivy.this,"shibai", 1).show();
    
   }
  });
  显示出传过来的json结果:
 
  
 

本文章只是自己学习笔记,大家要慎重借鉴





posted on 2013-12-03 14:30 何云隆 阅读(306) 评论(0)  编辑  收藏 所属分类: Android


只有注册用户登录后才能发表评论。


网站导航: