iLMS知識社群歷程檔登入
位置: 廖俊維 > Android
從android透過HttpGet連結ApacheTomcat取回資料顯示在ListView中
by 廖俊維 2012-12-01 21:48:17, 回應(0), 人氣(525)
首先準備一個table.jsp程式,放在ApacheTomcat的網站ROOT中,
被呼叫時,傳回一串資料:
<%@ page contentType="text/html;charset=utf-8" %>
<%
out.println("<RSPN>A,一中商圈");
out.println("<RSPN>B,一中商圈");
out.println("<RSPN>C,一中商圈");
out.println("<RSPN>D,一中商圈");
out.println("<RSPN>E,一中商圈");
out.println("<RSPN>F,一中商圈");
out.println("<RSPN>G,一中商圈");
%>
其中第1行,是確保傳到android端時的中文不會變亂碼。
接著在Android中建立一個專案,其中的主程式,假設叫Test2.java,
注意,在ListActivity的onCreate()方法中,不可以setContentView(),否則會有問題。

public class Test2 extends ListActivity {   

     private ArrayList<HashMap<String,String>> datas;

     public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          datas=new ArrayList<HashMap<String,String>>();
          GetURLDate();
     }

     private void GetURLDate() {
           try{
                     HttpClient client = new DefaultHttpClient();
                     String cmd = "http://163.17.84.153/table1.jsp";
                     HttpGet get = new HttpGet(cmd);
                     HttpResponse response = client.execute(get);
                     HttpEntity entity = response.getEntity();
                     BufferedReader reader = new BufferedReader( new InputStreamReader
                                                              (entity.getContent()));
                     String raw,msg="";
                     while ((raw = reader.readLine()) != null) {
                           if (raw.startsWith("<RSPN>"))
                               {
                                   msg=raw.substring(6);
                                   String []str1=msg.split(",");
                                   HashMap<String,String> item = new HashMap<String,String>();
                                   item.put("MarketName", str1[0]);
                                   item.put("MarketNameNO", str1[1]);
                                   datas.add(item);
                                }
                      }
                     SimpleAdapter adapter = new SimpleAdapter(this,datas,
                               android.R.layout.simple_list_item_2,
                               new String[] {"MarketName" , "MarketNameNO"},
                               new int[] { android.R.id.text1, android.R.id.text2 } );
                     setListAdapter(adapter);
                     getListView().setTextFilterEnabled(true);
                     reader.close();
                }catch (Exception ee){
                      System.out.println(ee.toString());
                }
        }
}
記得「android.permission.INTERNET」的權限要開放。
執行結果如下:
回應