簡體   English   中英

Android,使用PHP連接到MySQL

[英]Android, connecting to MySQL using PHP

我正在嘗試使用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;

?>

任何想法如何解決?

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

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

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

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

這樣,您將知道服務器上是否發生了某些事情。

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM