Tôi hiện đang cố gắng phát triển một ứng dụng mà trong số những thứ khác có thể gửi và nhận dữ liệu từ máy chủ mysql.Lấy dữ liệu từ mysql đến android bằng php
Ứng dụng gọi một tập lệnh php tạo kết nối tới máy chủ mysql. Tôi đã phát triển thành công phần gửi và bây giờ tôi muốn lấy dữ liệu từ mysql và hiển thị nó trên điện thoại Android.
Bảng mysql bao gồm 5 cột:
bssid
building
floor
lon
lat
Tệp php getdata.php
chứa:
<?php
$con = mysql_connect("localhost","root","xxx");
if(!$con)
{
echo 'Not connected';
echo ' - ';
}else
{
echo 'Connection Established';
echo ' - ';
}
$db = mysql_select_db("android");
if(!$db)
{
echo 'No database selected';
}else
{
echo 'Database selected';
}
$sql = mysql_query("SELECT building,floor,lon,lat FROM ap_location WHERE bssid='00:19:07:8e:f7:b0'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close(); ?>
Phần này hoạt động tốt khi được kiểm tra trong trình duyệt.
mã java để kết nối với php:
public class Database {
public static Object[] getData(){
String db_url = "http://xx.xx.xx.xx/getdata.php";
InputStream is = null;
String line = null;
ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
request.add(new BasicNameValuePair("bssid",bssid));
Object returnValue[] = new Object[4];
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httppost = new HttpPost(db_url);
httppost.setEntity(new UrlEncodedFormEntity(request));
HttpResponse response = httpclient.execute(httppost, localContext);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection" +e.toString());
}
String result = "";
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error in http connection" +e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
returnValue[0] = (json_data.getString("building"));
returnValue[1] = (json_data.getString("floor"));
returnValue[2] = (json_data.getString("lon"));
returnValue[3] = (json_data.getString("lat"));
}catch(JSONException e){
Log.e("log_tag", "Error parsing data" +e.toString());
}
return returnValue;
}
}
Đây là một mã sửa đổi sử dụng để gửi dữ liệu đến máy chủ mysql, nhưng cái gì là sai. Tôi đã thử để kiểm tra nó bằng cách thiết lập khác nhau returnValue
s trong mã và điều này cho thấy tôi rằng một phần với kết nối httpclient
không chạy.
Các bạn có thể giúp tôi không?
Tôi hy vọng điều này không quá khó hiểu, và nếu bạn muốn tôi có thể cố gắng giải thích nó hơn nữa.
BUMP. Tôi có cần phải giải thích thêm về vấn đề của mình không? – freddy
tôi đã kiểm tra mã và nó hoạt động tốt cho tôi. –
Bạn đã thêm quyền này vào tệp kê khai của mình chưa? ' ' –
Hovo