我正在尝试使用php脚本连接MySQL DB。但我没有得到任何输出只有异常代码。我无法弄清楚问题出在哪里。我使用了教程代码。
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;
&GT;
任何想法如何解决?
答案 0 :(得分:0)
首先,不要使用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.);
}
这样您就可以知道服务器上是否发生了某些事情。
希望这有帮助