I am creating a app which will show the data of MySQL table in the card_layout of the android app.
The below mentioned is the connection code in 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);
}
For the MySQL connection I am using PhP and executing in the XAMPP
server as localhost
, the code is as follows:
<?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);
?>
My table structure is as follows:
When I run this PhP file using browser then I am getting correct output as JSON array
:
But if I execute my app in android studio using emulator
I am getting java.net.SocketTimeoutException: connect timed out
The problem I am getting at the two lines of MainActivity.java
:
AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>()
Response response = client.newCall(request).execute();
I did research for a long time, please someone help me out.