尝试使用php将域服务器中的mysql数据显示到android应用程序,并将我的数据显示为toast消息。每当我运行应用程序时,我都会得到空的吐司。此外,我将使用列表视图来显示数据。代码中没有错误。下面是我的asychtask的代码:
class Connection extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String result = "";
String host = "http://prasaurus.com/conn.php";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
while ((line = reader.readLine()) != null ){
stringBuffer.append(line);
break;
}
reader.close();
result = stringBuffer.toString();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result){
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
}
}
以下是我在服务器端的php代码:
<?php
$db_name = "prasauru_FAND_DB";
$mysql_username = "###########"; #database name on server end
$mysql_password = "###########"; #database password
$server_name = "prasaurus.com";
$conn = mysqli_connect($server_name, $mysql_username, $mysql_password, $db_name);
if(!$conn){
die("Error in connection" . mysqli_connect_error());
}
$response = array();
$query = "SELECT * FROM `under8_club_league` ORDER BY `points` DESC";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)){
array_push($response , $row);
}
}
else {
$response['success'] = 0;
$response['message'] = 'No data';
}
echo json_encode($response);
mysqli_close($conn);
?>
2条答案
按热度按时间irtuqstp1#
你的代码不起作用。首先,你不需要在while循环中使用break。
第二,如果希望onpostexecute方法中的结果,应该返回它,而不是返回null。
您的代码已修复:
note:httpclient is 在新的android版本中不再支持了,因此我在代码中修改了这个。
希望对你有帮助。
wfypjpf42#
首先,您必须在清单文件中添加internet权限
然后是java代码
并使用如下函数