Th3Dark0 Th3Dark0 - 2 years ago 66
Android Question

Encountering android.os.NetworkOnMainThreadException while fetching data from a PHP script using Okhttp

I am making an android app.To fetch data from the app server running on my localhost using phpmyadmin, i am using below described php script:

<?php
$host = "localhost";
$db_user = "root" ;
$db_password = "" ;
$db_name = "FCM";

if(isset($_POST["Token"])){
$con = mysqli_connect($host,$db_user,$db_password,$db_name);

$sql = "select * from User";

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('UserName'=>$row[0], 'EmailID'=>$row[1], 'UID'=>$row[2]
));
}

echo json_encode(array("users"=>$result));

mysqli_close($con);
}
?>


And in my java class, in order to gather the response, I am using
Okhttp
and below described code:

public void getDataOKHTTP() {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder().add("Token","").build();
Request request = new Request.Builder().url("http://.........../fcm/test.php").post(body).build();
System.out.println("@ register a new token ");
try {
Response response= client.newCall(request).execute();
//response.header("Content-Type: application/json");
myJSON = response.body().string();
}catch (IOException e){
e.printStackTrace();
}
}


But when i run my app, i get,


com.example.apple.fetchdata, PID: 6092
android.os.NetworkOnMainThreadException.


I would be highly obliged if you could help me learn and resolve this problem.

thank you :)

Answer Source

All network operations has to be done on background thread, you're doing it on a main thread

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download