精華區beta AndroidDev 關於我們 聯絡資訊
這是之前在安卓板上我發的文 轉過來這邊跟大家分享 因為是直接轉錄 所以程式碼沒有貼去版主建議的分享網站 和板主說聲抱歉啦~ 如果真的很難懂 我再來修改 ====================================================================== 大家好~! 原po因為要做專題 研究了這部分好一陣子 google 還找不太到很完整的辦法 只能慢慢摸索 現在終於有小成果了 來跟大家分享一下連接方式 希望會幫助到需要的人:) 我只說明 比較重要的部分 ======================================================================== ***.java String uriAPI = "http://(這裡填sever ip)/***(php檔名稱).php"; HttpPost httpRequest = new HttpPost(uriAPI); //我是用httppost List <NameValuePair> params = new ArrayList <NameValuePair>(); params.add(new BasicNameValuePair("CatchNumber","2")); //這行的參數會自動加在uriAPI後面 以此例子來說 會變成 http://(這裡填sever ip)/***(php檔名稱).php?CatchNumber=2 如果後面還需要其他參數 方法相同 而此處的2為字串 如果需要int 再php還要再轉過(後面說明) try { httpRequest.setEntity( new UrlEncodedFormEntity(params,HTTP.UTF_8)); 這邊設成utf8 中文才不會亂碼 (但我還是亂碼目前還沒解決 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); if(httpResponse.getStatusLine().getStatusCode()==200) { String strResult = EntityUtils.toString (httpResponse.getEntity()); //資料庫抓過來後 我使用text列出 txv_Title.setText(strResult); } else { txv_Title.setText("Error Response:"+httpResponse.getStatusLine().toString()); } } catch (ClientProtocolException e) { txv_Title.setText(e.getMessage().toString()); e.printStackTrace(); } catch (IOException e) { txv_Title.setText(e.getMessage().toString()); e.printStackTrace(); } catch (Exception e) { txv_Title.setText(e.getMessage().toString()); e.printStackTrace(); } ====================================================================== ***.php <?php $link = mysql_connect("localhost","使用者名稱","密碼"); mysql_query("use (db名稱)"); $CatchNumber = $_POST["CatchNumber"]; //使用post接收java傳過來的CatchNumber intval("CatchNumber"); //String 轉 Int $result = mysql_query("select * from (表單) where No between '$CatchNumber' and '3'",$link); //此PHP語法很基本 不懂自己翻 //我要註明的是 這邊把CatchNumber的值 也就是2 從java抓過來使用了 while ($row = mysql_fetch_row($result)){ for($i=1;$i<count($row);$i++){ echo $row[$i]; echo " "; } } //上述為輸出方式 可依需要格式更改 mysql_free_result($result); mysql_close($link); ?> ====================================================================== 大概是這樣子 有什麼問題可以再詢問 (雖然我也不是很厲害XD ※ 編輯: nonebelieve 來自: 61.227.117.253 (01/13 23:44)
uranusjr:直接輸出如果資料比較複雜有點麻煩, 我在自己的 project 01/13 23:58
uranusjr:裡是用 JSON 包起來 01/13 23:58
nowar100:感謝分享,不照格式沒關係,只要確定版友看得懂就可以 01/14 00:35