2012-03-03 56 views
0

我試圖用php腳本連接到MySQL DB。但我沒有得到任何輸出只有異常代碼。我無法弄清楚問題出在哪裏。我使用了教程代碼。Android,使用PHP連接到MySQL

private EditText outputStream; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    String result = null; 
    InputStream input = null; 
    StringBuilder sbuilder = null; 
    outputStream = (EditText)findViewById(R.id.output); 
    ArrayList <NameValuePair> nameValuePairs = new ArrayList <NameValuePair>(); 

    try{ 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://ik.su.lt/~jbarzelis/Bandymas/index.php"); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     input = entity.getContent(); 
    } 
    catch(Exception e){ 
     Log.e("log_tag","Error in internet connection"+e.toString()); 
    } 
    try{ 
     BufferedReader reader = new BufferedReader(new InputStreamReader(input,"iso-8859-1"),8); 
     sbuilder = new StringBuilder(); 

     String line = null; 

     while((line = reader.readLine()) != null){ 
      sbuilder.append(line + "\n"); 
      System.out.println(line); 
     } 
     input.close(); 
     result = sbuilder.toString(); 
    } 
    catch(Exception e){ 
     Log.e("log_tag", "Error converting result "+e.toString());   
    } 
    int fd_id; 
    String fd_name; 
    try{ 
     JSONArray jArray = new JSONArray(result); 
     JSONObject json_data = null; 
     for(int i=0;i<jArray.length();i++){ 
      json_data = jArray.getJSONObject(i); 
      fd_id = json_data.getInt("FOOD_ID"); 
      fd_name = json_data.getString("FOOD_NAME"); 
      outputStream.append(fd_id +" " + fd_name + "\n"); 
     } 


     } 
    catch(JSONException e1){ 
     Toast.makeText(getBaseContext(), "No food found", Toast.LENGTH_LONG).show(); 
    } 
    catch(ParseException e1){ 
     e1.printStackTrace(); 
    } 
} 

PHP腳本:

<?php 
mysql_connect("localhost","**********","******"); 
mysql_select_db("test"); 
$sql = mysql_query("select FOOD_NAME as 'Maistas' from FOOD where FOOD_NAME like 'A%'"); 
while($row = mysql_fetch_assoc($sql)) $output[]=$row; 
print(json_encode($output)); 
mysql_close; 

>

任何想法如何解決這個問題?

+1

和什麼異常會是?如果它從PHP的例外是什麼,這與你的Android代碼的待辦事項?如果它的Java異常形式android的php部分是沒用的... – Rufinus 2012-03-03 17:24:14

+0

異常,說沒有找到食物 – Shien 2012-03-03 17:47:58

+0

03-03 20:08:35.182:DEBUG/SntpClient(40):請求時間失敗:java.net.SocketException :地址族不支持協議 這可能是一個主要問題? – Shien 2012-03-03 18:09:52

回答

0

首先,不使用Exception.toString(),使用Exception.printStackTrace():

catch (Exception e) { 
    e.printStackTrace(); 
} 

其次,在你的PHP代碼,你不檢查任何錯誤。如果發生任何錯誤,我建議你發出不同的HTTP狀態代碼(如400),那麼,在你的Android代碼:

if (response.getStatusLine().getStatusCode() != 200) { 
    Log.d("MyApp", "Server encountered an error.); 
} 

這樣,你就會知道,如果事情發生在服務器上。

希望這有助於