【发布时间】:2017-11-03 22:07:52
【问题描述】:
我正在创建一个应用程序,它将在 android 应用程序的 card_layout 中显示 MySQL 表的数据。
下面提到的是MainActivity.java中的连接代码
private void load_data_from_server(final int id) {
AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected Void doInBackground(Integer... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://10.10.2.2/develop/php_recyler_demo.php?id="+id).build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().toString());
for (int i=0; i<array.length(); i++) {
JSONObject object = array.getJSONObject(i);
MyData data = new MyData(object.getInt("id"),object.getString("description"),object.getString("image"));
data_list.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
对于我使用PhP并在XAMPP服务器中以localhost执行的MySQL连接,代码如下:
<?php
$connection = mysqli_connect("localhost","root","","test");
//$id = $_GET["id"];
$id = isset($_GET['id']) ? $_GET['id'] : '';
$query = "select * from recyclerdb where id between ($id+1) and ($id+4)";
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {
# code...
$array[] = $row;
}
header('Content-type:Application/json');
echo json_encode($array);
?>
当我使用浏览器运行这个 PhP 文件时,我得到正确的输出为JSON array:
但是如果我使用模拟器在 android studio 中执行我的应用程序
我收到java.net.SocketTimeoutException: connect timed out
我在MainActivity.java 的两行遇到的问题:
AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>()
Response response = client.newCall(request).execute();
我研究了很长时间,请有人帮助我。
【问题讨论】:
标签: java php android mysql android-asynctask